﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using MINERP.COM;
using MINERP.DAL;
using MINERP.MODEL.FoundationModel;
using MINERP.MODEL.NewPinBan;
using MINERP.COM.DBHelper;
using System.Data.SqlClient;

namespace MINERP.BLL.NewPB
{


    public delegate void GetFAutoPBResult(int result, float wrate, int Pnum, int overPnum);

    public class NewPBBLL
    {
        public delegate void StopPBDelete();

        public const int PHOTOSUBAREAID = 4; //照片分区的ID
        //public const int BARCODEWIDTH = 25;//条码点25个象素点宽
        public const int PERINCHTOSCREEN = 10; //1英寸=10屏（相素点）
        private const int MIN_ASC = 32;
        private const int MAX_ASC = 126;
        private const int NUM_ASC = 95;
        private readonly string _addr;
        private readonly int _port;
        private int[] BlackWidth = new Int32[3] {
													200,
													300,
													400
												};
        private int[] BlackWidthForce = new Int32[3] {
														10,
														15,
														20
													};
        private int[] BlackWidthLong = new Int32[3] {
														10,
														15,
														20
													};
        private int[] BlackWidthLowWaste = new Int32[3] {
															3,
															8,
															15
														};
        private int[] ComboxNum = new Int32[3] {
													2,
													3,
													4
												};
        private int[] ComboxNumForce = new Int32[3] {
														2,
														3,
														4
													};
        private int[] ComboxNumLong = new Int32[3] {
														2,
														3,
														4
													};
        private int[] ComboxNumLowWaste = new Int32[3] {
															2,
															3,
															4
														};
        private int[] CountLevel = new Int32[3] {
													0,
													0,
													0
												};
        private int[] CountLevelForce = new Int32[3] {
														3,
														4,
														5
													};
        private int[] CountLevelLong = new Int32[3] {
														0,
														0,
														0
													};
        private int[] CountLevelLowWaste = new Int32[3] {
															3,
															4,
															5
														};
        public bool IsAutoStop = false;
        public bool IsNewWhirl = false; //自动拼板是否又进行循环拼板
        private string _dogCode;
        private int changeLevel = 0;
        private int tryTime = 0;
        //LayoutDll.ClassInterFace InterFace = new LayoutDll.ClassInterFace();
        public NewPBBLL()
        {
            try
            {
                BARCODEWIDTH = IniFile.BarCodePixWidth;
                _addr = ConfigurationManager.AppSettings["RemoteIP"];
                _port = Convert.ToInt32(ConfigurationManager.AppSettings["RemotePort"]);
                //PBorderNum = Convert.ToInt32(ConfigurationManager.AppSettings["PBorderNum"]);
                WriteLogForCheck.WriteLogFile("ip:" + _addr + "port:" + _port);
            }
            catch (Exception)
            {
                _addr = "127.0.0.1";
                _port = 8888;
                PBorderNum = 30;
            }
        }
        public Printer_Info CurentPrinter { get; set; }
        public bool IsStop { get; set; } //是否停止自动拼板
        public bool HasStoped { get; set; } //是否已停止
        public int BARCODEWIDTH { get; set; }
        public int PBorderNum { get; set; }
        public event GetFAutoPBResult AutoPBResultEvent;
        public event StopPBDelete StopPBEvent;
        private string GetDogCode()
        {
            if (string.IsNullOrEmpty(_dogCode))
            {
                _dogCode = GetDogCode(_addr, _port);
                WriteLogForCheck.WriteLogFile("dogcode:" + _dogCode);
            }
            return _dogCode;
        }
        public int AutoCreateBoard(List<PhotoInfo_PinBan> PicList, Tb_paperTemplate_Info tb_paperTemplate_Info, Printer_Info printer_Info,
                                        int userId, float wasteRate, int realBoardLength)
        {
            int result = 1; //正常
            int MaxPriority = 0; //大板的加急级别
            string strPicPath; //大板图片要保存的路径
            int maxY = 0; //垂直方向自动居中     
            int disT = 0; //移动的距离
            paperFace pf;
            paperType pt;
            printer pr;
            Board b;
            photoInfo piTemp;
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                DbConnection conn = dataBase.Connection;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                DbTransaction tran = conn.BeginTransaction();
                try
                {
                    pf = dataBase.paperFace.FirstOrDefault(c => c.PaperFaceID == tb_paperTemplate_Info.PaperFaceId);
                    pt = dataBase.paperType.FirstOrDefault(c => c.PaperTypeID == tb_paperTemplate_Info.PaperTypeId);
                    pr = dataBase.printer.FirstOrDefault(p => p.PrinterID == tb_paperTemplate_Info.printerId);

                    //strPicPath = (dataBase.FileDirPath.FirstOrDefault(fp => fp.id == 3)).FileDir + "\\" + Guid.NewGuid().ToString() + ".jpg";
                    strPicPath = "\\";
                    b = new Board()
                    {
                        createTime = DateTime.Now,
                        DPI = printer_Info.PDPI,
                        length = realBoardLength,
                        paperFace = pf,
                        paperType = pt,
                        lastPrintTime = DateTime.Now,
                        printer = pr,
                        picPath = strPicPath,
                        width = Convert.ToInt32(tb_paperTemplate_Info.BoardHeight * printer_Info.PDPI),
                        Remark = "生成数据成功",
                        users = dataBase.users.FirstOrDefault(u => u.userID == userId),
                        status = (int)EnumBoardStatus.WaitSure,
                        printNumber = 0,
                        WasteRate = wasteRate < 0 ? 0 : wasteRate,
                        TempleteID = tb_paperTemplate_Info.TempLateId,

                    };

                    //向picmakeup表添加相关的信息
                    if (printer_Info.IsMiddlePrint)
                    {
                        //上下居中
                        maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.PixWidth : p.PixHeight) + (p.BarCodeStatus == 1 ? 25 : 0));
                        if (b.width - 25 > maxY)
                        {
                            disT = (b.width - 25 - maxY) / 2;
                        }
                    }
                    else
                    {
                        //maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.PixWidth : p.PixHeight) + (p.BarCodeStatus == 1 ? 25 : 0));

                        //if (b.width > maxY)
                        //{
                        //    disT = (b.width -maxY);
                        //}
                        disT = 0;
                    }
                    foreach (PhotoInfo_PinBan ph in PicList)
                    {
                        if (ph.IsClearBox == 1) //清柜的自动将加急级别升为最高
                        {
                            MaxPriority = 11;
                        }
                        if (ph.Priority > MaxPriority)
                        {
                            MaxPriority = ph.Priority;
                        }
                        piTemp = dataBase.photoInfo.FirstOrDefault(p => p.photoId == ph.PhotoId);
                        piTemp.status = (int)PhotoStatus.PingBan;
                        string encriptyX = "", encriptyY = "";

                        //encriptyX = EncryptPoint(ph.Location.X.ToString());
                        //encriptyY = EncryptPoint(disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString());

                        //if (string.IsNullOrEmpty(encriptyX) || string.IsNullOrEmpty(encriptyY))//加密失败
                        //{
                        //    return -2;//加密失败
                        //}
                        encriptyX = ph.Location.X.ToString();
                        encriptyY = disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString();
                        b.picMakeUp.Add(new picMakeUp()
                        {
                            BarCodeStatus = ph.BarCodeStatus,
                            photoInfo = piTemp,
                            IsWhirl = ph.IsWhirl,
                            Height = ph.PixHeight,
                            width = ph.PixWidth,
                            labelWidth = BARCODEWIDTH,
                            //X = encriptyX,
                            //Y = encriptyY,
                            X = ph.Location.X.ToString(), //不加密时用
                            Y = disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString(), //不加密时用
                            LABEL = ph.PhotoId.ToString()
                        });
                    }
                    b.printPriority = MaxPriority;
                    dataBase.AddToBoard(b);
                    dataBase.SaveChanges();
                    string widthCM = (b.width / (float)b.DPI * 2.54).ToString("0.00");
                    string heigthCM = ((b.length / (float)b.DPI * 2.54 * 100 + 80)).ToString("0.00")
;
                    ;                //更新大板的路径
                    //b.picPath = (dataBase.FileDirPath.FirstOrDefault(fp => fp.id == 3)).FileDir + "\\" + b.BoardId + "@" +
                    //b.createTime.ToString("yyMMddHHmm") + ".jpg";
                    b.picPath = (dataBase.FileDirPath.FirstOrDefault(fp => fp.id == 3)).FileDir + "\\" + b.BoardId + "@" +

                    widthCM + "x" + heigthCM + ".jpg";

                    dataBase.SaveChanges();
                    result = b.BoardId;
                    tran.Commit();
                    //BoardDDO bddo = new BoardDDO(b);
                    //bddo.picMakeUp = b.picMakeUp.ToList().ConvertAll(c => new picMakeUpDDO(c));
                    return result;
                }
                catch (UpdateException e)
                {
                    tran.Rollback();
                    result = -1; //添加数据时出错
                    WriteLogForCheck.WriteLogFile(DateTime.Now.ToString() + " 向board、picMakeUp表添加数据时出错：" + e.Message);
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
            return 0;
        }
        public static string GetDogCode(string addr, int port) //得到加密狗的CODE
        {
            string strResult = string.Empty;
            byte[] myReadBuffer = new byte[1024];
            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;
            try
            {
                client.Connect(addr, port);
                client.SendTimeout = 60 * 1000;
                client.ReceiveTimeout = 60 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 60 * 1000;
                byte[] myWriteBuffer = Encoding.Unicode.GetBytes("GD");
                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);
                int tryCount = 0;
                while (tryCount <= 3)
                {
                    int redLenth = 0;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        //return -2;//读取失败
                        strResult = string.Empty;
                        net.Close();
                        break;
                    }
                    if (redLenth > 0)
                    {
                        strResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }
                    tryCount++;
                }
                net.Close();
                return strResult;
            }
            catch (Exception)
            {
                return string.Empty;
            }
            finally
            {
                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }
            }
        }

        /// <summary>
        ///     得到所有的打印机
        /// </summary>
        /// <returns></returns>
        public List<Printer_Info> GetAllPrinter()
        {
            List<Printer_Info> listResult = new List<Printer_Info>();
            Printer_Info pi;
            string Xraystatus = Convert.ToString((int)PrinterType.Xray);
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                foreach (printer p in DataEntites.printer.Where(pt => pt.PType == Xraystatus).ToList())
                {
                    pi = new Printer_Info
                    {
                        IsTransverse = (bool)p.IsTransverse,
                        PDes = p.PDes,
                        PDPI = p.PDPI,
                        PrinterID = p.PrinterID,
                        ICCPath = p.ICCPath,
                        HotDirPath = p.hotDirPath,
                        PLength = (float)p.PLength,
                        PName = p.PName,
                        PType = p.PType,
                        PWidth = (float)p.PWidth,
                        Status = p.status,
                        Status2 = (int)p.status2,
                        IsMiddlePrint = (p.IsMiddlePrint == null) ? true : p.IsMiddlePrint
                    };
                    listResult.Add(pi);
                }
            }
            return listResult;
        }
        /// <summary>
        ///     得到某打印机所有的大板的模板
        /// </summary>
        /// <param name="printerId">打印机ID</param>
        /// <returns></returns>
        public List<Tb_paperTemplate_Info> GetAllTemplate(int printerId)
        {
            List<Tb_paperTemplate_Info> listResult = new List<Tb_paperTemplate_Info>();
            Tb_paperTemplate_Info pTempInfo;
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                foreach (tb_paperTemplate item in
                    DataEntites.tb_paperTemplate.Include("printer")
                                .Include("paperType")
                                .Include("paperFace")
                                .Where(pt => pt.printer.PrinterID == printerId)
                                .ToList())
                {
                    pTempInfo = new Tb_paperTemplate_Info
                    {
                        BoardHeight = item.boardHeight,
                        BoardLength = item.boardLength,
                        HasBarCode = item.haveBarCode,
                        PaperFaceId = item.paperFace.PaperFaceID,
                        PaperTypeId = item.paperType.PaperTypeID,
                        TempLateId = item.TempLateId,
                        TemplateName = item.TemplateName,
                        //                        PaperFaceName = item.paperFace.Name,
                        PaperTypeName = item.paperType.Name,
                        printerId = item.printer.PrinterID,
                        PaperFaceName = item.paperFace.Name,

                    };
                    listResult.Add(pTempInfo);
                }
            }
            return listResult;
        }

        ///// <summary>
        ///// 得到所有符合条件的照片列表
        ///// </summary>
        ///// <param name="printerId">打印机ID</param>
        ///// <param name="paperTypeId">纸型ID</param>
        ///// <param name="paperFaceId">纸面ID</param>
        ///// <returns></returns>
        //public List<PhotoInfo_PinBan> GetAllPhotos(int printerId, int paperTypeId, int paperFaceId)//得到符合要求的所有照片
        //{
        //    int photoStatus = (int)PhotoStatus.DistributedPrinter;//等待拼板
        //    int photoStatus2 = (int)PhotoStatus.PingBanInd;//正在拼板中
        //    int orderStatus = (int)OrderInfoStatus.Doing;

        //    List<PhotoInfo_PinBan> photoList = new List<PhotoInfo_PinBan>();

        //    using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
        //    {
        //        IQueryable<photoInfo> ResultList;
        //        try
        //        {
        //            ResultList = DataEntites.photoInfo.Where(p => p.orderInfo.status == orderStatus && p.printerId == printerId && p.paperFace.PaperFaceID == paperFaceId && p.paperType.PaperTypeID == paperTypeId && (p.status == photoStatus || p.status == photoStatus2));

        //            photoList = ConvertPiToPi_PingBan(ResultList.ToList());
        //        }
        //        catch (Exception)
        //        {

        //        }
        //        finally
        //        {
        //            if (DataEntites != null && DataEntites.Connection.State != System.Data.ConnectionState.Closed)
        //            {
        //                DataEntites.Connection.Close();
        //            }
        //        }
        //    }
        //    photoList = photoList.OrderByDescending(p => p.Priority).ThenBy(p => p.PhotoId).ToList();
        //    return photoList;
        //}
        /// <summary>
        ///     得到所有符合条件的照片列表
        /// </summary>
        /// <param name="printerId">打印机ID</param>
        /// <param name="paperTypeId">纸型ID</param>
        /// <param name="paperFaceId">纸面ID</param>
        /// <param name="showAllPapertypePhotos">是否显示全部纸型的照片,true 显示 false 不显示</param>
        /// <returns></returns>
        public List<PhotoInfo_PinBan> GetAllPhotos(int printerId, int paperTypeId, int paperFaceId, int temlpeteid, bool showAllPapertypePhotos,
                                                    Printer_Info printer, int boxCount)
        {
            if (boxCount == 0)
            {
                boxCount = 999;
            }
          
            List<PhotoInfo_PinBan> outPutPhotoList = new List<PhotoInfo_PinBan>();
            using (AdoEx adoEx = new AdoEx())
            {
                SqlParameter[] parms = new SqlParameter[3];
                parms[0] = new SqlParameter("printerId", SqlDbType.Int);
                parms[0].Value = printerId;
                parms[1] = new SqlParameter("materialID", SqlDbType.Int);
                parms[1].Value = temlpeteid;
                parms[2] = new SqlParameter("@BoxCount", SqlDbType.Int);

                parms[2].Value = boxCount;
                var reader = adoEx.ExecuteDataReader(CommandType.StoredProcedure, "proc_GetWaitPBPhotoInfoAll", parms);
                while (reader.Read())
                {
                    PhotoInfo_PinBan pi_PinBan = new PhotoInfo_PinBan();

                    pi_PinBan.IsWhirl = false;
                    pi_PinBan.Height = Convert.ToDouble(reader["Height"]);//Math.Round(pi.Height, 1);
                    pi_PinBan.Width = Convert.ToDouble(reader["Width"]);//Math.Round(pi.Width , 1);
                    pi_PinBan.Remark = reader["Remark"].ToString();
                    pi_PinBan.TotalNum = Convert.ToInt32(reader["TotalNum"]);
                    pi_PinBan.PixWidth = Convert.ToInt32(reader["PixWidth"]);
                    pi_PinBan.PixHeight = Convert.ToInt32(reader["PixHeight"]);
                    pi_PinBan.PicPath = reader["PicPath"].ToString();
                    pi_PinBan.OldPicPath = reader["OldPicPath"].ToString();
                    pi_PinBan.MakeUpNum = 1;
                    pi_PinBan.PhotoId = Convert.ToInt32(reader["PhotoId"]);
                    pi_PinBan.OrderInfoName = reader["OrderProductName"].ToString();
                    pi_PinBan.PhotoBarCode = reader["PhotoBarCode"].ToString(); ;
                    pi_PinBan.PhotoSize = pi_PinBan.Width + "*" + pi_PinBan.Height; //Math.Round(pi.Width + 0.04, 1) + "*" + Math.Round(pi.Height + 0.04, 1);
                    pi_PinBan.PhotoName = reader["PhotoName"].ToString(); ;
                    pi_PinBan.OrderProductId = Convert.ToInt32(reader["OrderProductId"]);
                    pi_PinBan.PaperFaceId = Convert.ToInt32(reader["PaperFaceId"]);
                    pi_PinBan.PaperFaceName = reader["PaperFaceName"].ToString();
                    pi_PinBan.PaperTypeID = Convert.ToInt32(reader["PaperTypeID"]);
                    pi_PinBan.PaperTypeName = reader["PaperTypeName"].ToString();
                    pi_PinBan.ShopName = reader["ShopName"].ToString(); ;
                    pi_PinBan.Priority = Convert.ToInt32(reader["Priority"]);
                    pi_PinBan.isPart = false;
                    pi_PinBan.IsInBoard = false;
                    pi_PinBan.IsClearBox = 0;
                    pi_PinBan.CtmName = reader["CtmName"].ToString(); ;
                    try
                    {
                        if (reader["DXFPath"] is DBNull)
                        {
                            pi_PinBan.DXFPath = "";
                        }
                        else
                        {
                            pi_PinBan.DXFPath = Convert.ToString(reader["DXFPath"]);
                        }

                        if (reader["DXFContent"] is DBNull)
                        {
                            //pi_PinBan.DXFContent = null;
                        }
                        else
                        {
                            pi_PinBan.DXFContent = (byte[])(reader["DXFContent"]);
                        }
                    }
                    catch
                    {

                    }

                    outPutPhotoList.Add(pi_PinBan);
                }
                if (reader.NextResult())
                {
                    while (reader.Read())
                    {
                        var item = new
                        {
                            OrderProductId = Convert.ToInt32(reader["OrderProductId"]),
                            photoAllNum = Convert.ToInt32(reader["photoAllNum"])
                        };
                        var listCurr = outPutPhotoList.Where(p => p.OrderProductId == item.OrderProductId).ToList();
                        if (listCurr.Count != item.photoAllNum)
                        {
                            listCurr.ForEach(each =>
                            {
                                each.isPart = true;
                            });
                        }
                    }

                }

            }
            return outPutPhotoList;
            //得到符合要求的所有照片
            //int photoStatus = (int) PhotoStatus.DistributedPrinter; //等待拼板
            //int photoStatus2 = (int) PhotoStatus.PingBanInd; //正在拼板中
            //int orderStatus = (int) OrderInfoStatus.Doing;
            //List<PhotoInfo_PinBan> photoList = new List<PhotoInfo_PinBan>();
            //using (newSampleYPDBEntities db = new newSampleYPDBEntities()) {
            //    List<photoInfo> resultList;
            //    try {
            //        if (showAllPapertypePhotos) {
            //            temlpeteid = -1;
            //        }
            //        resultList = db.proc_GetWaitPBPhotoInfo(printerId, temlpeteid, boxCount).ToList();
            //        photoList = ConvertPiToPi_PingBan(resultList, printerId, paperTypeId, paperFaceId, db, printer);
            //    }
            //    catch (Exception) {
            //    } finally {
            //        if (db.Connection.State != ConnectionState.Closed) {
            //            db.Connection.Close();
            //        }
            //    }
            //}
            //return GetWaitPBPhotoList();
            //photoList = photoList.OrderByDescending(p => p.Priority).ThenBy(p => p.PhotoId).ToList();
            // photoList;
        }

        
        public List<PhotoInfo_PinBan> GetWaitPBPhotoList(Tb_paperTemplate_Info inPutPaperTempte, int inPutPrinterID, int inPutTakeNum)
        {
            List<PhotoInfo_PinBan> outPutPhotoList = new List<PhotoInfo_PinBan>();
            using (AdoEx adoEx = new AdoEx())
            {
                SqlParameter[] parms = new SqlParameter[7];
                parms[0] = new SqlParameter("printerId", SqlDbType.Int);
                parms[0].Value = inPutPrinterID;
                parms[1] = new SqlParameter("materialID", SqlDbType.Int);
                parms[1].Value = inPutPaperTempte.TempLateId;
                parms[2] = new SqlParameter("inPutTakeNum", SqlDbType.Int);

                parms[2].Value = inPutTakeNum;
                var reader = adoEx.ExecuteDataReader(CommandType.StoredProcedure, "[proc_GetWaitPBPhotoInfoAll]", parms);
                while (reader.Read())
                {
                    PhotoInfo_PinBan pi_PinBan = new PhotoInfo_PinBan();

                    pi_PinBan.IsWhirl = false;
                    pi_PinBan.Height = Convert.ToDouble(reader["Height"]);//Math.Round(pi.Height, 1);
                    pi_PinBan.Width = Convert.ToDouble(reader["Width"]);//Math.Round(pi.Width , 1);
                    pi_PinBan.Remark = reader["Remark"].ToString();
                    pi_PinBan.TotalNum = Convert.ToInt16(reader["TotalNum"]);
                    pi_PinBan.PixWidth = Convert.ToInt16(reader["PixWidth"]);
                    pi_PinBan.PixHeight = Convert.ToInt16(reader["PixHeight"]);
                    pi_PinBan.PicPath = reader["PicPath"].ToString();
                    pi_PinBan.OldPicPath = reader["OldPicPath"].ToString();
                    pi_PinBan.MakeUpNum = Convert.ToInt16(reader["OldPicPath"]);
                    pi_PinBan.PhotoId = Convert.ToInt16(reader["PhotoId"]);
                    pi_PinBan.OrderInfoName = reader["OrderInfoName"].ToString();
                    pi_PinBan.PhotoBarCode = reader["PhotoBarCode"].ToString(); ;
                    pi_PinBan.PhotoSize = pi_PinBan.Width + "*" + pi_PinBan.Height; //Math.Round(pi.Width + 0.04, 1) + "*" + Math.Round(pi.Height + 0.04, 1);
                    pi_PinBan.PhotoName = reader["PhotoName"].ToString(); ;
                    pi_PinBan.OrderProductId = Convert.ToInt16(reader["OrderProductId"]);

                    pi_PinBan.ShopName = reader["ShopName"].ToString(); ;
                    pi_PinBan.Priority = Convert.ToInt16(reader["Priority"]);
                    pi_PinBan.isPart = false;
                    pi_PinBan.IsInBoard = false;
                    pi_PinBan.IsClearBox = 0;
                    pi_PinBan.CtmName = reader["CtmName"].ToString(); ;

                    outPutPhotoList.Add(pi_PinBan);
                }

            }
            return outPutPhotoList;
        }
        //public List<PhotoInfo_PinBan> GetWaitPBPhoto(int printId, int[] mid, Printer_Info pinter) {
        //    using (newSampleYPDBEntities db = new newSampleYPDBEntities()) {
        //        var wmMaterialItem = db.WM_MaterialItem.Where(c => mid.Contains(c.MID)).ToArray();
        //        List<PhotoInfo_PinBan> rval = new List<PhotoInfo_PinBan>();
        //        foreach(int m in mid) {
        //            List<photoInfo> resultList = db.proc_GetWaitPBPhotoInfo(printId, m, 99999).ToList();

        //            List<PhotoInfo_PinBan> convertPiToPiPingBan = ConvertPiToPi_PingBan(resultList, pinter, wmMaterialItem);
        //            rval.AddRange(convertPiToPiPingBan);
        //        }

        //        //				List<photoInfo> photoInfoDdos = db.photoInfo.Where(c => c.printerId == printId && mid.Contains(c.MaterialId ?? 0)).ToList();
        //        //				List<PhotoInfo_PinBan> convertPiToPiPingBan = ConvertPiToPi_PingBan(photoInfoDdos);
        //        rval = rval.OrderByDescending(p => p.Priority).ThenBy(p => p.PhotoId).ToList();
        //        //				.ToList().ConvertAll(c => new photoInfoDDO(c));
        //        return rval;
        //    }
        //}
        //public List<PhotoInfo_PinBan> ConvertPiToPi_PingBan(List<photoInfo> piSource, Printer_Info printerId,WM_MaterialItem[]  wmMaterialItem)
        //    //将photoinfo转换成PhotoInfo_PinBan
        //{
        //    List<PhotoInfo_PinBan> photoList = new List<PhotoInfo_PinBan>();
        //    PhotoInfo_PinBan pi_PinBan;
        //    //if (PBorderNum <= 0)
        //    //{
        //    //    PBorderNum = 30;
        //    //}
        //    List<int> orderProductIdList = new List<int>();
        //    foreach(photoInfo pi in piSource) {
        //        pi.status = (int) PhotoStatus.PingBanInd; //标记被占用,正在拼板中....

        //        #region load data

        //        if (!pi.orderInfoReference.IsLoaded) {
        //            pi.orderInfoReference.Load();
        //        }
        //        if (!pi.orderInfo.Tb_OrderBagReference.IsLoaded) {
        //            pi.orderInfo.Tb_OrderBagReference.Load();
        //        }
        //        if (!pi.orderInfo.Tb_OrderBag.ShopReference.IsLoaded) {
        //            pi.orderInfo.Tb_OrderBag.ShopReference.Load();
        //        }
        //        if (!pi.paperFaceReference.IsLoaded) {
        //            pi.paperFaceReference.Load();
        //        }
        //        if (!pi.paperTypeReference.IsLoaded) {
        //            pi.paperTypeReference.Load();
        //        }

        //        #endregion

        //        pi_PinBan = new PhotoInfo_PinBan();
        //        pi_PinBan.CtmName = pi.orderInfo.CtmName;
        //        pi_PinBan.IsClearBox = pi.status2;
        //        pi_PinBan.IsInBoard = false;
        //        pi_PinBan.IsWhirl = false;
        //        pi_PinBan.Height = pi.Height;
        //        pi_PinBan.Width = pi.Width;
        //        pi_PinBan.Remark = pi.Remark;
        //        pi_PinBan.TotalNum = pi.TotalNum == null ? 0 : (int) pi.TotalNum;
        //        pi_PinBan.PixWidth = (int) (printerId.PDPI*pi.Width);
        //        pi_PinBan.PixHeight = (int) (printerId.PDPI*pi.Height);
        //        pi_PinBan.PicPath = pi.picPath;
        //        pi_PinBan.OldPicPath = pi.OldPicPath;
        //        pi_PinBan.MakeUpNum = pi.MakeUpNum == null ? 0 : (int) pi.MakeUpNum;
        //        pi_PinBan.PhotoId = pi.photoId;
        //        pi_PinBan.OrderInfoName = pi.orderInfo.OrderProductName;
        //        pi_PinBan.PhotoBarCode = pi.PhotoBarCode;
        //        pi_PinBan.PhotoSize = pi.Width.ToString("f2") + "*" + pi.Height.ToString("f2");
        //        pi_PinBan.PhotoName = pi.photoName;
        //        pi_PinBan.OrderProductId = pi.orderInfo.OrderProductId;
        //        pi_PinBan.ShopName = pi.orderInfo.Tb_OrderBag.Shop.shopName;
        //        pi_PinBan.Priority = pi.orderInfo.Priority == null ? 0 : (int) pi.orderInfo.Priority;
        //        if (!orderProductIdList.Contains(pi_PinBan.OrderProductId)) {
        //            orderProductIdList.Add(pi_PinBan.OrderProductId);
        //        }
        //        var firstOrDefault = wmMaterialItem.FirstOrDefault(c => c.MID == pi.MaterialId);
        //        if (firstOrDefault != null) {
        //            pi_PinBan.MatName = firstOrDefault.Name;
        //        }
        //        if (PBorderNum > 0) {
        //            if (orderProductIdList.Count > PBorderNum) {
        //                return photoList;
        //            }
        //        }
        //        photoList.Add(pi_PinBan);
        //    }
        //    return photoList;
        //}
        private List<PhotoInfo_PinBan> ConvertPiToPi_PingBan(List<photoInfo> piSource, int printerId, int paperTypeId, int paperFaceId,
                                                            newSampleYPDBEntities db, Printer_Info printer) //将photoinfo转换成PhotoInfo_PinBan
        {
            //IEnumerable<int?> matArr = piSource.Select(c => c.MaterialId);
            //var wmMaterialItem = db.WM_MaterialItem.Where(c => matArr.Contains(c.MID)).Select(c => new { c.MID, c.Name }).ToArray();
            List<PhotoInfo_PinBan> photoList = new List<PhotoInfo_PinBan>();
            PhotoInfo_PinBan pi_PinBan;
            //if (PBorderNum <= 0)
            //{
            //    PBorderNum = 30;
            //}
            int photoStatus = (int)PhotoStatus.DistributedPrinter; //等待拼板
            int photoStatus2 = (int)PhotoStatus.PingBanInd; //正在拼板中
            List<int> orderProductIdList = new List<int>();
            //if (!pi.orderInfoReference.IsLoaded)
            //{
            //    pi.orderInfoReference.Load();
            //}
            piSource.ForEach(eh => eh.orderInfoReference.Load());
            foreach (IGrouping<int, photoInfo> pGroup in piSource.GroupBy(g => g.orderInfo.OrderProductId))
            {
                int orderproductid = pGroup.Key;
                bool ispicPart = false;
                int picnum = piSource.Count(p => p.orderInfo.OrderProductId == orderproductid);
                int picAllNum =
                    db.photoInfo.Count(
                        p =>
                        p.orderInfo.OrderProductId == orderproductid && p.printerId == printerId && p.paperFace.PaperFaceID == paperFaceId &&
                        p.paperType.PaperTypeID == paperTypeId);
                if (picAllNum != picnum)
                {
                    ispicPart = true;
                }
                foreach (photoInfo pi in pGroup)
                {
                    pi.status = (int)PhotoStatus.PingBanInd; //标记被占用,正在拼板中....

                    #region load data

                    if (!pi.orderInfo.Tb_OrderBagReference.IsLoaded)
                    {
                        pi.orderInfo.Tb_OrderBagReference.Load();
                    }
                    if (!pi.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        pi.orderInfo.Tb_OrderBag.ShopReference.Load();
                    }
                    if (!pi.paperFaceReference.IsLoaded)
                    {
                        pi.paperFaceReference.Load();
                    }
                    if (!pi.paperTypeReference.IsLoaded)
                    {
                        pi.paperTypeReference.Load();
                    }

                    #endregion

                    pi_PinBan = new PhotoInfo_PinBan();
                    pi_PinBan.IsWhirl = false;
                    pi_PinBan.Height = pi.Height;
                    pi_PinBan.Width = pi.Width;
                    pi_PinBan.Remark = pi.Remark;
                    pi_PinBan.TotalNum = pi.TotalNum == null ? 0 : (int)pi.TotalNum;
                    pi_PinBan.PixWidth = (int)(pi.Width * printer.PDPI);
                    pi_PinBan.PixHeight = (int)(pi.Height * printer.PDPI);
                    pi_PinBan.PicPath = pi.picPath;
                    pi_PinBan.OldPicPath = pi.OldPicPath;
                    pi_PinBan.MakeUpNum = pi.MakeUpNum == null ? 0 : (int)pi.MakeUpNum;
                    pi_PinBan.PhotoId = pi.photoId;
                    pi_PinBan.OrderInfoName = pi.orderInfo.OrderProductName;
                    pi_PinBan.PhotoBarCode = pi.PhotoBarCode;
                    pi_PinBan.PhotoSize = pi.Width.ToString("f2") + "*" + pi.Height.ToString("f2");
                    pi_PinBan.PhotoName = pi.photoName;
                    pi_PinBan.OrderProductId = pi.orderInfo.OrderProductId;
                    pi_PinBan.ShopName = pi.orderInfo.Tb_OrderBag.Shop.shopName;
                    pi_PinBan.Priority = pi.orderInfo.Priority == null ? 0 : (int)pi.orderInfo.Priority;
                    pi_PinBan.isPart = ispicPart;
                    pi_PinBan.IsInBoard = false;
                    pi_PinBan.IsClearBox = pi.status2;
                    pi_PinBan.CtmName = pi.orderInfo.CtmName;
                    pi_PinBan.PaperFaceId = pi.paperFace.PaperFaceID;
                    pi_PinBan.PaperFaceName = pi.paperFace.Name;
                    pi_PinBan.PaperTypeID = pi.paperType.PaperTypeID;
                    pi_PinBan.PaperTypeName = pi.paperType.Name;
                    if (!orderProductIdList.Contains(pi_PinBan.OrderProductId))
                    {
                        orderProductIdList.Add(pi_PinBan.OrderProductId);
                    }
                    if (PBorderNum > 0)
                    {
                        if (orderProductIdList.Count > PBorderNum)
                        {
                            return photoList;
                        }
                    }
                    //var firstOrDefault = wmMaterialItem.FirstOrDefault(c => c.MID == pi.MaterialId);
                    //if (firstOrDefault != null)
                    //{
                    //    pi_PinBan.MatName = firstOrDefault.Name;
                    //}
                    //wmMaterialItem.FirstOrDefault(c => c.MID == pi.MaterialId).Name;// wmMaterialItem.Name;
                    photoList.Add(pi_PinBan);
                }
            }
            return photoList;
        }
        //		public List<PhotoInfo_PinBan> GetClearBoxPhotos(int printerId, int PaperTypeId, int paperFaceId) //得到所有“以格子占用最少为优先”算法的照片列表
        //		{
        //			List<PhotoInfo_PinBan> resultList = new List<PhotoInfo_PinBan>(); //返回的结果集
        //			GridSubArea subArea; //照片分区           
        //			List<int> orderProductIdList; //正在分片的产品ID列表           
        //			orderInfo tempOi; //临时的           
        //			int photoStatus = (int) PhotoStatus.DistributedPrinter; //等待拼板
        //			int photoStatus2 = (int) PhotoStatus.PingBanInd; //正在拼板中
        //			using (newSampleYPDBEntities db = new newSampleYPDBEntities()) {
        //				subArea = db.GridSubArea.FirstOrDefault(sa => sa.SubAreaID == PHOTOSUBAREAID);
        //				if (subArea == null) {
        //					return resultList;
        //				}
        //				if (!subArea.Grid.IsLoaded) {
        //					subArea.Grid.Load();
        //				}
        //				orderProductIdList = subArea.Grid.ToList().Select(g => g.SomeId).ToList();
        //				orderProductIdList = orderProductIdList.Where(g => g != 0).ToList();
        //				foreach(int orderProductId in orderProductIdList) {
        //					tempOi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
        //					if (tempOi == null) {
        //						continue;
        //					}
        //					if (!tempOi.photoInfo.IsLoaded) {
        //						tempOi.photoInfo.Load();
        //					}
        //					photoInfo firstPi = tempOi.photoInfo.FirstOrDefault();
        //					if (firstPi == null) {
        //						continue;
        //					}
        //					if (!firstPi.paperFaceReference.IsLoaded) {
        //						firstPi.paperFaceReference.Load();
        //					}
        //					if (!firstPi.paperTypeReference.IsLoaded) {
        //						firstPi.paperTypeReference.Load();
        //					}
        //					if (firstPi.paperType.PaperTypeID != PaperTypeId || firstPi.paperFace.PaperFaceID != paperFaceId || firstPi.printerId != printerId) {
        //						continue;
        //					}
        //					resultList.AddRange(
        //						ConvertPiToPi_PingBan(tempOi.photoInfo.ToList().Where(p => p.status == photoStatus || p.status == photoStatus2).ToList()));
        //				}
        //			}
        //			resultList.ForEach(p => p.IsClearBox = 1);
        //			return resultList;
        //		}
        //		public List<PhotoInfo_PinBan> GetPhotoByPorduct(int printerId, int PaperTypeId, int paperFaceId)
        //			//得到“已拼板”、“未打印”的照片所对应的那些还未拼板的照片列表----以产品优先
        //		{
        //			List<PhotoInfo_PinBan> resultList = new List<PhotoInfo_PinBan>(); //返回的结果集
        //			int pStatus = (int) PhotoStatus.Printed; //已打印  
        //			int pStatus2 = (int) PhotoStatus.PingBan; //已拼板  
        //			int photoStatus = (int) PhotoStatus.DistributedPrinter; //等待拼板  
        //			int photoStatus2 = (int) PhotoStatus.PingBanInd; //正在拼板中  
        //			List<orderInfo> oiList;
        //			using (newSampleYPDBEntities db = new newSampleYPDBEntities()) {
        //				oiList =
        //					db.photoInfo.Where(
        //						p =>
        //						p.printerId == printerId && p.paperFace.PaperFaceID == paperFaceId && p.paperType.PaperTypeID == PaperTypeId &&
        //						(p.status == pStatus || p.status == pStatus2)).Select(p => p.orderInfo).ToList();
        //				oiList = oiList.Distinct(new MyOrderInfoCompare()).ToList();
        //				foreach(orderInfo oi in oiList) {
        //					if (!oi.photoInfo.IsLoaded) {
        //						oi.photoInfo.Load();
        //					}
        //					resultList.AddRange(ConvertPiToPi_PingBan(oi.photoInfo.Where(p => p.status == photoStatus || p.status == photoStatus2).ToList()));
        //				}
        //			}
        //			return resultList;
        //		}
        /// <summary>
        ///     向board表和picmakeup表添加信息
        /// </summary>
        /// <param name="PicList">照片列表</param>
        /// <param name="tb_paperTemplate_Info">模板</param>
        /// <param name="printer_Info"></param>
        /// <param name="userId">操作员</param>
        /// <param name="wasteRate">浪费率</param>
        /// <param name="realBoardLength">英寸长</param>
        /// <returns>0--表示正常，1--表示在保存时出错</returns>
        public int CreateBoard(List<PhotoInfo_PinBan> PicList, Tb_paperTemplate_Info tb_paperTemplate_Info, Printer_Info printer_Info, int userId,
                                float wasteRate, int realBoardLength, int boardType)
        {
            //boardLength单位：英寸
            //PicList中的location为屏幕上的坐标
            int boardLength = realBoardLength;

            //photo的location的坐标转换
            //			PicList.ForEach(p => {
            //				int x, y;
            //				x = Convert.ToInt32((float) p.Location.X/PERINCHTOSCREEN*CurentPrinter.PDPI);
            //				y = (int) ((float) p.Location.Y/PERINCHTOSCREEN*CurentPrinter.PDPI);
            //				p.Location = new Point(x, y);
            //			});
            if (PicList.Max(p => p.Location.X >= boardLength) ||
                PicList.Max(p => p.Location.Y >= tb_paperTemplate_Info.BoardHeight * printer_Info.PDPI))
            {
                return -1;
            }
            return CreateBoard2(PicList, tb_paperTemplate_Info, printer_Info, userId, wasteRate, boardLength, boardType);
        }
        /// <summary>
        ///     加密坐标X、Y
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public string EncryptPoint(string strInput)
        {
            if (string.IsNullOrEmpty(_dogCode))
            {
                try
                {
                    _dogCode = GetDogCode();
                }
                catch (Exception)
                {
                    return string.Empty;
                }
                if (string.IsNullOrEmpty(_dogCode))
                {
                    return string.Empty;
                }
            }
            string key = _dogCode.Substring(0, 8); //前八位为KEY
            string encryptDogCode = _dogCode.Substring(8);
            string dogKey = Decipher(encryptDogCode, key);
            return Cipher(dogKey, strInput);
        }

        //加密
        public string Cipher(string key, string input)
        {
            char[] random = key.ToCharArray();
            char[] from_text = input.ToCharArray();
            StringBuilder result = new StringBuilder();
            char[] buf1 = new char[from_text.Length];
            int offset;
            int str_len = 1;
            int i;
            int ch;
            str_len = from_text.Length;
            try
            {
                for (i = 0; i < str_len; i++)
                {
                    ch = from_text[i];
                    if (ch >= MIN_ASC && ch <= MAX_ASC)
                    {
                        ch = ch - MIN_ASC;
                        offset = (NUM_ASC + 1) * random[i];
                        ch = (ch + offset) % NUM_ASC;
                        ch = ch + MIN_ASC;
                        buf1[i] = (char)ch;
                    }
                    else
                    {
                        buf1[i] = from_text[i];
                    }
                }
                foreach (char item in buf1)
                {
                    result.Append(item);
                }
            }
            catch (Exception)
            {
                result = new StringBuilder("");
            }
            return result.ToString();
        }
        //解密
        public string Decipher(string strFromText, string key)
        {
            StringBuilder result = new StringBuilder();
            char[] random = key.ToCharArray();
            char[] from_text = strFromText.ToCharArray();
            char[] buf1 = new char[strFromText.Length];
            int offset;
            int str_len = 1;
            int i;
            int ch;
            str_len = from_text.Length;
            try
            {
                for (i = 0; i < str_len; i++)
                {
                    ch = from_text[i];
                    if (ch >= MIN_ASC && ch <= MAX_ASC)
                    {
                        ch = ch - MIN_ASC;
                        offset = (NUM_ASC + 1) * random[i];
                        ch = (ch - offset) % NUM_ASC;
                        if (ch < 0)
                        {
                            ch = ch + NUM_ASC;
                        }
                        ch = ch + MIN_ASC;
                        buf1[i] = (char)ch;
                    }
                    else
                    {
                        buf1[i] = from_text[i];
                    }
                }
                foreach (char item in buf1)
                {
                    result.Append(item);
                }
            }
            catch (Exception)
            {
                result = new StringBuilder("");
            }
            return result.ToString();
        }
        /// <summary>
        ///     所有的关于长度、宽度、坐标信息全是“图片”上的象素为单位
        /// </summary>
        /// <param name="PicList"></param>
        /// <param name="tb_paperTemplate_Info"></param>
        /// <param name="printer_Info"></param>
        /// <param name="userId"></param>
        /// <param name="wasteRate"></param>
        /// <param name="realBoardLength"></param>
        /// <returns>-2加解密失败</returns>
        public int CreateBoard2(List<PhotoInfo_PinBan> PicList, Tb_paperTemplate_Info tb_paperTemplate_Info, Printer_Info printer_Info, int userId,
                                float wasteRate, int realBoardLength, int boardType)
        {
            int result = 0; //正常
            int MaxPriority = 0; //大板的加急级别
            string strPicPath; //大板图片要保存的路径
            int maxY = 0; //垂直方向自动居中     
            int disT = 0; //移动的距离
            paperFace pf;
            paperType pt;
            printer pr;
            Board b;
            photoInfo piTemp;
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                DbConnection conn = dataBase.Connection;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                DbTransaction tran = conn.BeginTransaction();
                try
                {
                    pf = dataBase.paperFace.FirstOrDefault(p => p.PaperFaceID == tb_paperTemplate_Info.PaperFaceId);
                    pt = dataBase.paperType.FirstOrDefault(p => p.PaperTypeID == tb_paperTemplate_Info.PaperTypeId);
                    pr = dataBase.printer.FirstOrDefault(p => p.PrinterID == tb_paperTemplate_Info.printerId);

                    //strPicPath = (dataBase.FileDirPath.FirstOrDefault(fp => fp.id == 3)).FileDir + "\\" + Guid.NewGuid().ToString() + ".jpg";
                    strPicPath = "\\";
                    b = new Board
                    {
                        createTime = DateTime.Now,
                        DPI = printer_Info.PDPI,
                        length = realBoardLength,
                        paperFace = pf,
                        paperType = pt,
                        lastPrintTime = DateTime.Now,
                        printer = pr,
                        picPath = strPicPath,
                        width = Convert.ToInt32(tb_paperTemplate_Info.BoardHeight * printer_Info.PDPI),
                        Remark = "生成数据成功",
                        users = dataBase.users.FirstOrDefault(u => u.userID == userId),
                        status = (int)EnumBoardStatus.waitProduct,
                        printNumber = 0,
                        WasteRate = wasteRate < 0 ? 0 : wasteRate,
                        BoardType = boardType
                    };
                    //b.MaterialItemId = tb_paperTemplate_Info.MaterialItemId;

                    //向picmakeup表添加相关的信息
                    if (pr.IsMiddlePrint)
                    { //上下居中
                        maxY = PicList.Max(p => (p.Location.Y + (p.IsWhirl ? p.PixWidth : p.PixHeight)));
                        if (b.width - BARCODEWIDTH > maxY)
                        {
                            disT = (b.width - BARCODEWIDTH - maxY) / 2;
                        }
                    }
                    else
                    {
                        //maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.PixWidth : p.PixHeight) + (p.BarCodeStatus == 1 ? 25 : 0));

                        //if (b.width > maxY)
                        //{
                        //    disT = (b.width -maxY);
                        //}
                        disT = 0;
                    }
                    foreach (PhotoInfo_PinBan ph in PicList)
                    {
                        if (ph.IsClearBox == 1) //清柜的自动将加急级别升为最高
                        {
                            MaxPriority = 11;
                        }
                        if (ph.Priority > MaxPriority)
                        {
                            MaxPriority = ph.Priority;
                        }
                        piTemp = dataBase.photoInfo.FirstOrDefault(p => p.photoId == ph.PhotoId);
                        piTemp.status = (int)PhotoStatus.PingBan;
                        string encriptyX = "", encriptyY = "";
                        //						encriptyX = EncryptPoint(ph.Location.X.ToString());
                        //						encriptyY = EncryptPoint(disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString());
                        //						if (string.IsNullOrEmpty(encriptyX) || string.IsNullOrEmpty(encriptyY)) //加密失败
                        //						{
                        //							return -2; //加密失败
                        //						}
                        b.picMakeUp.Add(new picMakeUp
                        {
                            BarCodeStatus = ph.BarCodeStatus,
                            photoInfo = piTemp,
                            IsWhirl = ph.IsWhirl,
                            Height = ph.PixHeight,
                            width = ph.PixWidth,
                            labelWidth = BARCODEWIDTH,
                            //X = encriptyX,
                            //Y = encriptyY,
                            X = ph.Location.X.ToString(), //不加密时用
                            Y = disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString(), //不加密时用
                            LABEL = ph.PhotoId.ToString()
                        });
                    }
                    b.printPriority = MaxPriority;
                    dataBase.AddToBoard(b);
                    dataBase.SaveChanges();
                    string widthCM = (b.width / (float)b.DPI * 2.54).ToString("0.00");
                    string heigthCM = (b.length / (float)b.DPI * 2.54 * 100 + 80).ToString("0.00");
                    //更新大板的路径
                    b.picPath = (dataBase.FileDirPath.FirstOrDefault(fp => fp.id == 3)).FileDir + "\\" + b.BoardId + "@" +
                                widthCM + "x" + heigthCM + ".jpg";
                    dataBase.SaveChanges();
                    tran.Commit();
                }
                catch (UpdateException e)
                {
                    tran.Rollback();
                    result = 1; //添加数据时出错
                    WriteLogForCheck.WriteLogFile(DateTime.Now + " 向board、picMakeUp表添加数据时出错：" + e.Message);
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
            return result;
        }
        /// <summary>
        ///     删除模板
        /// </summary>
        /// <param name="curTemplateId"></param>
        /// <returns>0-正常,1-未找要删除的模板,2-保存数据库进出错</returns>
        public int DelTemplate(int curTemplateId)
        {
            int result = 0; //代表正常
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                tb_paperTemplate tp = dataBase.tb_paperTemplate.FirstOrDefault(p => p.TempLateId == curTemplateId);
                if (tp == null)
                {
                    result = 1;
                }
                else
                {
                    dataBase.DeleteObject(tp);
                }
                try
                {
                    dataBase.SaveChanges();
                }
                catch (UpdateException)
                {
                    result = 2;
                }
            }
            return result;
        }
        /// <summary>
        ///     添加新的模板，0正常，1-错误
        /// </summary>
        /// <param name="strTemplateName"></param>
        /// <param name="paperFaceId"></param>
        /// <param name="paperTypeId"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="hasBarCode"></param>
        /// <param name="printerId"></param>
        /// <returns>0正常，1-错误</returns>
        public int AddNewTemplate(string strTemplateName, int paperFaceId, int paperTypeId, float width, float height, bool hasBarCode,
                                int printerId)
        {
            int result = 0; //正常
            printer pT;
            paperFace pf;
            paperType pt;
            try
            {
                using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
                {
                    pT = dataBase.printer.FirstOrDefault(p => p.PrinterID == printerId);
                    pf = dataBase.paperFace.FirstOrDefault(p => p.PaperFaceID == paperFaceId);
                    pt = dataBase.paperType.FirstOrDefault(p => p.PaperTypeID == paperTypeId);
                    tb_paperTemplate newT = new tb_paperTemplate
                    {
                        TemplateName = strTemplateName,
                        haveBarCode = hasBarCode,
                        printer = pT,
                        paperFace = pf,
                        paperType = pt,
                        boardHeight = height,
                        boardLength = width,
                        //MaterialItemID = materialItemId
                    };
                    dataBase.AddTotb_paperTemplate(newT);
                    dataBase.SaveChanges();
                }
            }
            catch (UpdateException)
            {
                result = 1;
            }
            return result;
        }
        /// <summary>
        ///     修改模板0--正常 ，1--未找到要修改的模板，2--更新出错
        /// </summary>
        /// <param name="tempInfo"></param>
        /// <returns></returns>
        public int ModifyTemplate(Tb_paperTemplate_Info tempInfo)
        {
            int result = 0; //正常
            tb_paperTemplate pT;
            paperFace pf;
            paperType pt;
            try
            {
                using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
                {
                    pf = dataBase.paperFace.FirstOrDefault(f => f.PaperFaceID == tempInfo.PaperFaceId);
                    pt = dataBase.paperType.FirstOrDefault(t => t.PaperTypeID == tempInfo.PaperTypeId);
                    pT = dataBase.tb_paperTemplate.FirstOrDefault(p => p.TempLateId == tempInfo.TempLateId);
                    //                    if (pt == null) {
                    //                        result = 1;
                    //                    }
                    //                    else
                    //                    {
                    pT.boardLength = tempInfo.BoardLength;
                    pT.boardHeight = tempInfo.BoardHeight;
                    pT.haveBarCode = tempInfo.HasBarCode;
                    pT.TemplateName = tempInfo.TemplateName;
                    pT.paperFace = pf;
                    pT.paperType = pt;
                    //pT.MaterialItemID = tempInfo.MaterialItemId;
                    dataBase.SaveChanges();
                    //                    }
                }
            }
            catch (Exception)
            {
                result = 2;
            }
            return result;
        }
        public List<PaperFace_Info> GetAllPaperFace()
        {
            List<PaperFace_Info> listPaperFace = new List<PaperFace_Info>();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                foreach (paperFace pf in dataBase.paperFace.ToList())
                {
                    PaperFace_Info pfi = new PaperFace_Info { Name = pf.Name, PaperFaceID = pf.PaperFaceID, Remark = pf.remark };
                    listPaperFace.Add(pfi);
                }
            }
            return listPaperFace;
        }
        public List<PaperType_Info> GetAllPaperType()
        {
            List<PaperType_Info> listPti = new List<PaperType_Info>();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                foreach (paperType pt in dataBase.paperType.Include("BoardWidth").ToList())
                {
                    PaperType_Info pti = new PaperType_Info
                    {
                        Name = pt.Name,
                        PaperTypeID = pt.PaperTypeID,
                        Remark = pt.remark,
                        DefaultWidthID = pt.BoardWidth.BoardWidthID
                    };
                    listPti.Add(pti);
                }
            }
            return listPti;
        }
        public List<BoardWidth_Info> GetSuitPaperWidthByPaperTypeId(int _selectedPaperTypeId) //得到某纸型所对应的纸宽列表
        {
            List<BoardWidth_Info> listBwi = new List<BoardWidth_Info>();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                paperType pt = dataBase.paperType.FirstOrDefault(t => t.PaperTypeID == _selectedPaperTypeId);
                if (pt != null)
                {
                    pt.BoardWidth1.Load();
                    foreach (BoardWidth bw in pt.BoardWidth1.ToList())
                    {
                        BoardWidth_Info bwi = new BoardWidth_Info { Width = bw.Width, WidthId = bw.BoardWidthID };
                        listBwi.Add(bwi);
                    }
                }
            }
            return listBwi;
        }
        //public int FAutoPB(float wrate, Tb_paperTemplate_Info template, int opUid, Printer_Info printerInfo)
        //{
        //    int reulst = 0;  //方法返回结果          
        //    int minPUnm = 0;  //当照片数小于300时执行从数据库重新获取新的照片列表          
        //    int totalPnum = 0;  //此次待拼板的照片的总数          
        //    int maxX = 0;  //某次拼板结果的最大X值,真实的相素pixel        
        //    float maxLeng = 0;  //MaxX换算成英寸,真实的相素pixel        
        //    int pBresult = 0;  //向数据库添加大板的结果          
        //    int totalArea = 0;  //某次拼板结果的大图的面积          
        //    int factArea = 0;  //此大图上有效照片的总面积          
        //    float factRaste = 0;  //某次拼板的实际浪费率          

        //    List<PhotoInfo_PinBan> listPSource = new List<PhotoInfo_PinBan>();   //待拼板的照片集      
        //    List<PhotoInfo_PinBan> priorityPsource = new List<PhotoInfo_PinBan>();   //据有优先拼板的照片集合      
        //    List<PhotoInfo_PinBan> resultP = new List<PhotoInfo_PinBan>();   //拼板结果的照片集      

        //    while (true)
        //    {
        //        if (minPUnm < 300)
        //        {
        //            listPSource = GetAllPhotos(template.printerId, template.PaperTypeId, template.PaperFaceId);
        //            minPUnm = listPSource.Count;
        //        }

        //        if (minPUnm < 1)
        //        {
        //            reulst = 1;
        //            break;
        //        }
        //        if (totalPnum == 0)
        //        {
        //            totalPnum = minPUnm;
        //        }
        //        resultP.Clear();
        //        resultP = AutoPinS(listPSource, template);

        //        if (resultP.Count < 1)
        //        {
        //            reulst = 2;
        //            break;
        //        }
        //        maxX = resultP.Max(p => p.Location.X + (p.IsWhirl ? p.PixHeight : p.PixWidth));//真实的相素
        //        totalArea = Convert.ToInt32(template.BoardHeight * printerInfo.PDPI) * maxX;
        //        factArea = resultP.Sum(p => p.PixWidth * p.PixHeight);
        //        factRaste = 1 - (float)factArea / totalArea;
        //        if (factRaste > wrate)
        //        {
        //            foreach (var p in resultP)
        //            {
        //                p.IsInBoard = false;
        //            }

        //            continue;
        //        }

        //        maxLeng = (float)maxX / printerInfo.PDPI;//真实的英寸
        //        pBresult = CreateBoard(resultP, template, printerInfo, opUid, factRaste, maxLeng);
        //        if (pBresult == 1)
        //        {
        //            reulst = 3;
        //            break;
        //        }
        //        minPUnm = listPSource.Count(p => !p.IsInBoard);

        //        AutoPBResultEvent(pBresult, factRaste, minPUnm, totalPnum - minPUnm);

        //    }
        //    return reulst;
        //}
        /// <summary>
        ///     全自动拼板
        /// </summary>
        /// <param name="wrate">浪费率</param>
        /// <param name="template">大板的模板</param>
        /// <param name="opUid">操作员</param>
        /// <returns>1--没有图片可拼,2--无法自动拼出图片,3--向数据库保存图片时出错，所以退出自动拼板</returns>
        /// <summary>
        ///     全自动拼板算法
        /// </summary>
        /// <param name="wrate"></param>
        /// <param name="template"></param>
        /// <param name="opUid"></param>
        /// <param name="printerInfo"></param>
        /// <param name="barCodeStatus"></param>
        /// <returns></returns>
        //		public int FAUTOPB(float wrate, Tb_paperTemplate_Info template, int opUid, Printer_Info printerInfo, int barCodeStatus) {
        //			int result = 0; //方法返回结果 
        //			List<PhotoInfo_PinBan> listPSource = new List<PhotoInfo_PinBan>(); //待拼板的照片集
        //			List<PhotoInfo_PinBan> PriorityPsource = new List<PhotoInfo_PinBan>(); //据有优先拼板的照片集合
        //			List<PhotoInfo_PinBan> resultP = new List<PhotoInfo_PinBan>(); //拼板结果的照片集
        //			while (!IsStop) {
        //				AutoPBResultEvent(5, 0, 0, 0);
        //				PriorityPsource = GetClearBoxPhotos(template.printerId, template.MaterialItemId, template.PaperFaceId); //先得到清柜的那些照片
        //				listPSource = PriorityPsource;
        //				AutoPBResultEvent(8, 0, 0, listPSource.Count);
        //				result = PB(wrate, template, opUid, printerInfo, listPSource, 0, null, barCodeStatus);
        //				if (IsStop) {
        //					break;
        //				}
        //				if (result == 2) { //获得新的数据源
        //					AutoPBResultEvent(5, 0, 0, 0);
        //					PriorityPsource = PriorityPsource.Where(p => !p.IsInBoard).ToList();
        //					PriorityPsource.AddRange(GetPhotoByPorduct(template.printerId, template.MaterialItemId, template.PaperFaceId)); //再得到按产品优先的那些照片
        //					PriorityPsource = PriorityPsource.Distinct(new MyPhotoComparer()).ToList();
        //					listPSource = PriorityPsource;
        //					result = PB(wrate, template, opUid, printerInfo, listPSource, 0, null, barCodeStatus);
        //					if (IsStop) {
        //						break;
        //					}
        //					if (result == 2) //获得新的数据源,即所有照片，然后将那些优先的照片采用“替换的方式”拼到板中
        //					{
        //						AutoPBResultEvent(5, 0, 0, 0);
        //						PBorderNum = -1; //就表示取得所有的
        //						listPSource = GetAllPhotos(template.printerId, 1, 1, template.MaterialItemId, false);
        //						AutoPBResultEvent(9, 0, 0, listPSource.Count);
        //						result = PB(wrate, template, opUid, printerInfo, listPSource, 1, PriorityPsource.Where(p => !p.IsInBoard).ToList(), barCodeStatus);
        //						if (result == 3) //向数据库添加数据时出错
        //						{
        //						}
        //					}
        //				}
        //				break;
        //			}
        //			//HasStoped = true;
        //			if (StopPBEvent != null) {
        //				StopPBEvent();
        //			}
        //			return result;
        //		}

        //help method
        private void ReSetList(ref List<PhotoInfo_PinBan> sourceList)
        {
            sourceList = sourceList.Where(p => !p.IsInBoard).ToList();
            foreach (PhotoInfo_PinBan pi in sourceList)
            {
                pi.IsAutoPB = false;
            }
        }
        //		private int PB(float wrate, Tb_paperTemplate_Info template, int opUid, Printer_Info printerInfo, List<PhotoInfo_PinBan> sourceList,
        //						int type, List<PhotoInfo_PinBan> prioritySourceList, int barCodeStatus) //将给定的数据源进行拼板
        //		{
        //			AutoPBResultEvent(6, 0, 0, 0);
        //			int result = 0;
        //			int MaxLeng = 0;
        //			int PBresult = 0; //向数据库添加大板的结果
        //			float factRaste = 0;
        //			List<PhotoInfo_PinBan> resultP = new List<PhotoInfo_PinBan>(); //拼板结果的照片集
        //			while (true) {
        //				resultP.Clear();
        //				resultP = AllAutoPB(sourceList, template, wrate, printerInfo, barCodeStatus);
        //				result = CheckPBResult(wrate, resultP, template, printerInfo, out factRaste, out MaxLeng);
        //				if (result == 0) {
        //					#region //用优先级里的图片替换拼板结果里的图片 if type=0则是正常的方式
        //
        //					if (type == 1 && prioritySourceList != null && prioritySourceList.Count > 1) {
        //						prioritySourceList = prioritySourceList.Except(resultP, new MyPhotoComparer()).ToList();
        //						foreach(PhotoInfo_PinBan pi in resultP) {
        //							PhotoInfo_PinBan pT = prioritySourceList.Where(p1 => !p1.IsInBoard).ToList().Find(delegate(PhotoInfo_PinBan p) {
        //								if ((p.PhotoId != pi.PhotoId) &&
        //									((p.PSize.Width == pi.PSize.Width && p.PSize.Height == pi.PSize.Height) ||
        //									(p.PSize.Width == pi.PSize.Height && p.PSize.Height == pi.PSize.Width))) {
        //									return true;
        //								}
        //								return false;
        //							});
        //							if (pT != null) //找到了，则替换掉
        //							{
        //								pi.IsInBoard = false;
        //								pi.IsWhirl = false;
        //								pT.IsInBoard = true;
        //								if (pT.PixWidth == pi.PixWidth && pT.PixHeight == pi.PixHeight) {
        //									pT.IsWhirl = pi.IsWhirl;
        //								}
        //								else {
        //									pT.IsWhirl = !pi.IsWhirl;
        //								}
        //							}
        //						}
        //						resultP.AddRange(prioritySourceList.Where(p2 => p2.IsInBoard).ToList());
        //						resultP = resultP.Where(p => p.IsInBoard).ToList();
        //						prioritySourceList = prioritySourceList.Where(p => !p.IsInBoard).ToList();
        //					}
        //
        //					#endregion
        //
        //					PBresult = CreateBoard(resultP, template, printerInfo, opUid, factRaste, MaxLeng);
        //					if (PBresult == 1) {
        //						result = 3;
        //						; //在向数据库添加数据时出错，则退出     
        //						break;
        //					}
        //					if (type == 1) //如果是普通的拼板就退出了
        //					{
        //						break;
        //					}
        //					ReSetList(ref sourceList);
        //				}
        //				if (result == 1 || result == 2) //无法完成拼板需要新的数据源
        //				{
        //					result = 2;
        //					break;
        //				}
        //				result = 3;
        //				break;
        //			}
        //			return result;
        //		}

        //检果自动拼板的结果
        private int CheckPBResult(float wrate, List<PhotoInfo_PinBan> resultP, Tb_paperTemplate_Info template, Printer_Info printerInfo,
                                out float factRaste, out int maxX)
        {
            AutoPBResultEvent(4, 0, 0, 0);
            maxX = 0; //某次拼板结果的最大X值
            factRaste = 0; //某次拼板的实际浪费率
            if (resultP.Count < 1)
            {
                return 2; //拼板结果无，则退出
            }
            factRaste = GetPBResultRate(resultP, template, printerInfo, out maxX);
            AutoPBResultEvent(7, factRaste, 0, 0);
            if (factRaste > wrate)
            {
                foreach (PhotoInfo_PinBan p in resultP)
                {
                    p.IsInBoard = false;
                }
                //重新再拼,继续拼
                return 1;
            }
            AutoPBResultEvent(0, factRaste, 0, resultP.Count);
            return 0; //检查成功，可以进行向数据库进行添加数据操作
        }

        //得到拼板结果的浪费率
        private float GetPBResultRate(List<PhotoInfo_PinBan> resultP, Tb_paperTemplate_Info template, Printer_Info printerInfo)
        {
            int maxX = 0;
            return GetPBResultRate(resultP, template, printerInfo, out maxX);
        }
        /// <summary>
        ///     得到拼板结果的浪费率
        /// </summary>
        /// <param name="resultP"></param>
        /// <param name="template"></param>
        /// <param name="printerInfo"></param>
        /// <returns></returns>
        private float GetPBResultRate(List<PhotoInfo_PinBan> resultP, Tb_paperTemplate_Info template, Printer_Info printerInfo, out int maxX)
        {
            maxX = 0; //某次拼板结果的最大X值
            float factRaste = 0; //某次拼板的实际浪费率
            int totalArea = 0; //某次拼板结果的大图的面积
            int factArea = 0; //此大图上有效照片的总面积
            maxX = resultP.Max(p => (p.Location.X + (p.IsWhirl ? p.PixHeight : p.PixWidth) + (template.HasBarCode ? BARCODEWIDTH : 0))); //真实的相素
            totalArea = Convert.ToInt32(template.BoardHeight * printerInfo.PDPI) * maxX;
            if (template.HasBarCode)
            {
                factArea = resultP.Sum(p => p.IsWhirl ? p.PixWidth * (p.PixHeight + BARCODEWIDTH) : (p.PixWidth + BARCODEWIDTH) * (p.PixHeight));
            }
            else
            {
                factArea = resultP.Sum(p => p.PixWidth * p.PixHeight);
            }
            factRaste = 1 - (float)factArea / totalArea;
            return factRaste;
        }
        /// <summary>
        ///     最全面的全自动拼板，即将所有的照片都拿按不同的组合进行拼板，取浪费率最低的那组
        /// </summary>
        /// <param name="sourcePList"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public List<PhotoInfo_PinBan> AllAutoPB(List<PhotoInfo_PinBan> sourcePList, Tb_paperTemplate_Info template, float rate,
                                                Printer_Info printer, int barCodeStatus)
        {
            float factRaste;
            List<PhotoInfo_PinBan> listResult = new List<PhotoInfo_PinBan>();
            List<PhotoInfo_PinBan> ListTempResult;
            while (!IsNewWhirl)
            {
                ListTempResult = AutoPinS(sourcePList, template, barCodeStatus);
                if (ListTempResult.Count < 1)
                {
                    listResult = ListTempResult;
                    break;
                }
                factRaste = GetPBResultRate(ListTempResult, template, printer);
                if (factRaste <= rate)
                {
                    listResult = ListTempResult;
                    //if (listResult.Find(p => p.PhotoId == 16967 || p.PhotoId == 18041) != null)
                    //{
                    //    Debug.WriteLine("");
                    //}
                    return listResult;
                }
            }
            foreach (PhotoInfo_PinBan pi in sourcePList.Where(p => p.IsAutoPB).ToList())
            {
                pi.IsAutoPB = false;
                pi.IsInBoard = false;
            }
            IsNewWhirl = false;
            return listResult;
        }
        /// <summary>
        ///     半自动拼板算法
        /// </summary>
        /// <param name="sourcePList">待拼板的数据</param>
        /// <param name="template">board模板</param>
        /// <returns>符合要求的照片包括有坐标信息</returns>
        public List<PhotoInfo_PinBan> AutoPinS(List<PhotoInfo_PinBan> sourcePList, Tb_paperTemplate_Info template, int barCodeStatus)
        {
            int boardMinX = 12; //打印机最小的出版长度               
            int bordHeight = Convert.ToInt32(template.BoardHeight * CurentPrinter.PDPI);
            int boardLenght = Convert.ToInt32(template.BoardLength * CurentPrinter.PDPI);
            Point PLocation = new Point(0, 0); //图片的坐标,以实际的大纸的坐标为准    
            Point Re_Point1 = new Point(0, 0); //剩余空间的启始坐标    
            Size Re_Size1 = new Size(0, 0); //剩余空间的SIZE    
            Point Re_Point2 = new Point(0, 0); //剩余空间的启始坐标    
            Size Re_Size2 = new Size(0, 0); //剩余空间的SIZE    
            List<PhotoInfo_PinBan> resultList = new List<PhotoInfo_PinBan>();

            #region 特殊的自动拼板

            List<PhotoInfo_PinBan> tempList = sourcePList.Where(p => !p.IsAutoPB).ToList();
            if (tempList.Count < 3)
            {
                IsNewWhirl = true;
                foreach (PhotoInfo_PinBan p in sourcePList)
                {
                    p.IsAutoPB = false;
                    p.IsInBoard = false;
                }
            }
            else
            {
                sourcePList = tempList;
            }
            List<Size> listS =
                sourcePList.Where(p => bordHeight % p.PSize.Width == 0 || bordHeight % p.PSize.Height == 0)
                            .Select(p => p.PSize)
                            .Distinct(new MySizeComparer())
                            .ToList();
            List<PhotoInfo_PinBan> someSizePList = new List<PhotoInfo_PinBan>();
            foreach (Size s in listS)
            {
                int row_colum = 0; //每一列有最多最放多少张图片
                int fact_colum = 0; //此Size的图片实际可以放多少列
                Size sT = s;

                //if (template.HasBarCode)
                //{
                //    sT.Width += BARCODEWIDTH;
                //}
                //if (barCodeStatus == 1)
                //{ sT.Width += BARCODEWIDTH; }
                //else if (barCodeStatus == 0)
                //{
                //    sT.Height += BARCODEWIDTH;
                //}
                if (bordHeight % sT.Height == 0)
                {
                    row_colum = bordHeight / sT.Height;
                }
                else if (bordHeight % sT.Width == 0)
                {
                    row_colum = bordHeight / sT.Width;
                    sT.Width = s.Height;
                    sT.Height = s.Width;
                }
                else
                {
                    continue;
                }
                sT.Width += BARCODEWIDTH;
                if (barCodeStatus == 1)
                {
                    someSizePList =
                        sourcePList.Where(
                            p =>
                            (!p.IsInBoard && (p.PixHeight == sT.Height && p.PixWidth == sT.Width - BARCODEWIDTH) ||
                            sT.Width - BARCODEWIDTH == p.PixHeight && sT.Height == p.PixWidth)).Distinct(new MyPhotoComparer()).ToList();
                }
                else if (barCodeStatus == 0)
                {
                    someSizePList =
                        sourcePList.Where(
                            p =>
                            (!p.IsInBoard && (p.PixHeight == sT.Height - BARCODEWIDTH && p.PixWidth == sT.Width) ||
                            sT.Width == p.PixHeight && sT.Height - BARCODEWIDTH == p.PixWidth)).Distinct(new MyPhotoComparer()).ToList();
                }
                else //无条码
                {
                    someSizePList =
                        sourcePList.Where(
                            p => (!p.IsInBoard && (p.PixHeight == sT.Height && p.PixWidth == sT.Width) || sT.Width == p.PixHeight && sT.Height == p.PixWidth))
                                    .Distinct(new MyPhotoComparer())
                                    .ToList();
                }
                int pNum = someSizePList.Count; //此种尺寸的图片总数
                if (pNum >= row_colum)
                {
                    int fact_columT = pNum / row_colum;
                    fact_colum = boardLenght / sT.Width;
                    if (fact_columT < fact_colum)
                    {
                        fact_colum = fact_columT;
                    }
                    for (int colum = 0; colum < fact_colum; colum++)
                    {
                        if (PLocation.X + sT.Width > boardLenght)
                        {
                            break;
                        }
                        for (int pic = 0; pic < row_colum; pic++)
                        {
                            PhotoInfo_PinBan p = someSizePList.OrderByDescending(pt => pt.Priority).FirstOrDefault(pt => !pt.IsInBoard);
                            if (p == null)
                            {
                                break;
                            }
                            if (barCodeStatus == 1) //条码在左右
                            {
                                if (p.PixHeight == sT.Width - BARCODEWIDTH)
                                {
                                    p.IsWhirl = true;
                                }
                            }
                            else //无条码或是条码在下面
                            {
                                if (p.PixHeight == sT.Width)
                                {
                                    p.IsWhirl = true;
                                }
                            }
                            p.IsInBoard = true;
                            p.IsAutoPB = true;
                            p.BarCodeStatus = barCodeStatus;
                            p.Location = PLocation;
                            PLocation.Y += sT.Height;
                            resultList.Add(p);
                        }
                        PLocation.X += sT.Width; //换列时
                        PLocation.Y = 0; //换列时X=0
                    }
                }
            }

            #endregion

            if (resultList.Count < 1) //启用普通的拼板方法
            {
                #region 正常的自动拼板

                PLocation = new Point(0, 0);
                Size source_Size = new Size(boardLenght, bordHeight);
                Re_AutoPB(ref sourcePList, PLocation, source_Size, ref resultList, barCodeStatus);

                #endregion
            }
            else
            {
                #region 测试用，测查是否有重叠现像

                //if (resultList.Count > 0)
                //{
                //    List<PhotoInfo_PinBan> temp1List = resultList.Distinct(new PhotoSizeCompare()).ToList();
                //    if (temp1List.Count != resultList.Count)
                //    {
                //        Debug.WriteLine("此板出现重叠");
                //    }
                //}

                #endregion

                //已拼好的版的长度是否符合要求
                if (resultList.Max(p => p.Location.X + (p.IsWhirl ? p.PixHeight : p.PixWidth)) < boardMinX)
                {
                    foreach (PhotoInfo_PinBan p in resultList)
                    {
                        p.IsWhirl = false;
                        p.IsInBoard = false;
                        p.Location = new Point(0, 0);
                    }
                    resultList.Clear();
                    PLocation = new Point(0, 0);
                    Size source_Size = new Size(boardLenght, bordHeight);
                    Re_AutoPB(ref sourcePList, PLocation, source_Size, ref resultList, barCodeStatus);
                }
            }

            #region 测试用，测查是否有重叠现像

            //if (resultList.Count > 0)
            //{
            //    List<PhotoInfo_PinBan> temp2List = resultList.Distinct(new PhotoSizeCompare()).ToList();
            //    if (temp2List.Count != resultList.Count)
            //    {
            //        Debug.WriteLine("此板出现重叠");
            //    }
            //}

            #endregion

            return resultList;
        }
        //public List<PhotoInfo_PinBan> AutoPinSN21(List<PhotoInfo_PinBan> sourcePList, Tb_paperTemplate_Info template, Printer_Info CurentPrinter, decimal waste, out decimal outWaste, out int outCurrLength, int minLength, bool isForcePrint, int autoModel)
        //{
        //    //isForcePrint = isForcePrint;

        //    waste = waste / 100;

        //    ///最小宽度
        //    int boardMinX = Convert.ToInt32(12 * CurentPrinter.PDPI);//打印机最小的出版长度

        //    int suitMinX = Convert.ToInt32(0.7 * template.BoardLength * CurentPrinter.PDPI);//打印机最小的出版长度
        //    ///板宽  
        //    int boardHeight = Convert.ToInt32(template.BoardHeight * CurentPrinter.PDPI);
        //    ///版长
        //    int boardLenght = Convert.ToInt32(template.BoardLength * CurentPrinter.PDPI);
        //    int MinX = Convert.ToInt32(template.BoardLength * ((float)minLength / 100) * CurentPrinter.PDPI);//打印机最小的出版长度
        //    //int boardMinXVal=
        //    Point PLocation = new Point(0, 0);  //图片的坐标,以实际的大纸的坐标为准  
        //    outCurrLength = 0;//记录真实照片长度

        //    foreach (PhotoInfo_PinBan photo in sourcePList)
        //    {

        //        photo.PixFactHeigth = Convert.ToInt32(Convert.ToDecimal(photo.PixHeight));
        //        photo.PixFactWidth = Convert.ToInt32(Convert.ToDecimal(photo.PixWidth));
        //        photo.IsInBoard = false;
        //        photo.IsWhirl = false;
        //        //photo.TryTime = 0;
        //    }
        //    //sourcePList = ColnePhotoList(sourcePList);
        //    PLocation = new Point(0, 0);
        //    Size source_Size = new Size(boardLenght, boardHeight);
        //    List<PhotoInfo_PinBan> resultList = new List<PhotoInfo_PinBan>();
        //    List<Line> VerticalLine = new List<Line>();///存放拼过的竖线
        //    List<Point> CurrVLinePhotoPoint = new List<Point>();
        //    List<MyRectangle> listRect = new List<MyRectangle>();

        //    Rectangle currRectang = new Rectangle(new Point(0, 0), new Size(boardLenght, boardHeight));//当前矩形框
        //    int currWidth = 0;//记录当前要补充的块的宽
        //    int tempHeight = boardHeight;
        //    int maxWidth = boardLenght;
        //    int outHeightLeft;
        //    int outWidthLeft;

        //    //用户计算回滚操作
        //    bool CanPut = false;//标志该版可以结束
        //    //int CanPutNum = 0;//可以出的前几张
        //    double CanPutWaste = 1;//当前的浪费率rr

        //    List<int> CutPhotoidList = new List<int>();//将能够出的照片暂存
        //    Rectangle CutRectangle = new Rectangle();//达到回滚条件时的最小矩形框
        //    double currWate = 0;
        //    //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "数据准备成功");
        //    while (true)
        //    {

        //        //try
        //        //{

        //        List<PhotoInfo_PinBan> TSPlist;
        //        try
        //        {
        //            TSPlist = sourcePList.Where(p => p.IsInBoard == false && ((p.PixFactHeigth <= boardHeight && p.PixFactWidth <= boardLenght) || (p.PixFactHeigth <= boardLenght && p.PixFactWidth <= boardHeight))).ToList(); ;
        //            if (TSPlist.Count == 0)
        //            {
        //                CanPutWaste = currWate;
        //                CutPhotoidList = new List<int>();
        //                foreach (PhotoInfo_PinBan photoct in resultList)
        //                {
        //                    CutPhotoidList.Add(photoct.PhotoId);
        //                }
        //                break;//直接出因为没有照片了
        //            }
        //            if (IsAutoStop)
        //            {
        //                resultList.ForEach(p => p.IsInBoard = false);

        //                resultList = new List<PhotoInfo_PinBan>();
        //                break;
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            throw new Exception("初始化 出错");
        //        }

        //        #region//处理照片放置顺序
        //        int putPhotoOrder = -1;//0照片宽度按照小大排 1照片宽度按照大小排-1初始值
        //        Point leftTop = currRectang.Location;//左上定点
        //        Point leftBottom = new Point(currRectang.Location.X, currRectang.Location.Y + currRectang.Height);//坐下顶点
        //        try
        //        {
        //            if ((leftBottom.Y - leftTop.Y) == boardHeight)
        //            {
        //                putPhotoOrder = 1;
        //            }
        //            else
        //            {
        //                if (leftTop.Y == 0)
        //                {
        //                    putPhotoOrder = 1;
        //                }
        //                if (leftTop.Y != 0 && leftBottom.Y == boardHeight)
        //                {
        //                    putPhotoOrder = 0;
        //                }
        //                if (putPhotoOrder == -1)
        //                {
        //                    var topRect1 = listRect.Where(p => p.LeftBottomPoint.X < leftTop.X && p.RightBottomPoint.X >= leftTop.X);
        //                    MyRectangle topRect = listRect.FirstOrDefault(p => p.LeftBottomPoint.X <= leftTop.X && p.RightBottomPoint.X > leftTop.X && p.LeftBottomPoint.Y == leftTop.Y);
        //                    MyRectangle bottomRect = listRect.FirstOrDefault(p => p.LeftTopPoint.X <= leftBottom.X && p.RighTopPoint.X > leftBottom.X && p.LeftTopPoint.Y == leftBottom.Y);
        //                    if (topRect == null || bottomRect == null)
        //                    {
        //                        putPhotoOrder = 1;
        //                    }
        //                    if (topRect != null && bottomRect != null)
        //                    {
        //                        int topLength = topRect.RighTopPoint.X - leftTop.X;
        //                        int bottomLength = bottomRect.RightBottomPoint.X - leftBottom.X;
        //                        if (topLength >= bottomLength)
        //                        {
        //                            putPhotoOrder = 0;
        //                        }
        //                        else
        //                        {
        //                            putPhotoOrder = 1;
        //                        }
        //                    }

        //                }

        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            throw new Exception("计算顺序出错");
        //        }
        //        #endregion

        //        #region//获取要拼版的照片
        //        //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "确定照片顺序成功");
        //        List<PhotoInfo_PinBan> PhotoList = new List<PhotoInfo_PinBan>();
        //        try
        //        {
        //            if (!isForcePrint)//普通模式
        //            {
        //                PhotoList = FindSuitPhotos21(TSPlist, currRectang, template.BarCodeStatus, out outHeightLeft, sourcePList, putPhotoOrder, template, CurentPrinter, MinX, autoModel, CurrVLinePhotoPoint);
        //            }
        //            else//加急模式
        //            {
        //                if (TSPlist.Where(ph => ph.Priority == 1).ToList().Count != 0)
        //                {
        //                    if (resultList.Count == 0 || VerticalLine.Count == 1)//强制输出的情况下照片第一章照片强制取照片
        //                    {
        //                        PhotoList = FindSuitPhotosForce(TSPlist.Where(ph => ph.Priority == 1).ToList(), currRectang, template.BarCodeStatus, out outHeightLeft, sourcePList, putPhotoOrder, template, CurentPrinter, MinX, CurrVLinePhotoPoint);
        //                    }
        //                    else//其他情况下 先加急的排如果木有 再按普通模式按普通模式
        //                    {
        //                        PhotoList = FindSuitPhotosForce(TSPlist.Where(ph => ph.Priority == 1).ToList(), currRectang, template.BarCodeStatus, out outHeightLeft, sourcePList, putPhotoOrder, template, CurentPrinter, MinX, CurrVLinePhotoPoint);

        //                        if (PhotoList == null || PhotoList.Count == 0)
        //                        {
        //                            PhotoList = FindSuitPhotos21(TSPlist, currRectang, template.BarCodeStatus, out outHeightLeft, sourcePList, putPhotoOrder, template, CurentPrinter, MinX, autoModel, CurrVLinePhotoPoint);
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    PhotoList = FindSuitPhotos21(TSPlist, currRectang, template.BarCodeStatus, out outHeightLeft, sourcePList, putPhotoOrder, template, CurentPrinter, MinX, autoModel, CurrVLinePhotoPoint);
        //                }

        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            throw new Exception("取照片出错");
        //        }
        //        #endregion

        //        if (PhotoList == null || PhotoList.Count == 0)
        //        {
        //            // WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "获取不到照片");
        //            //try
        //            //{
        //            #region//找不到合适的照片来放
        //            try
        //            {
        //                if (VerticalLine.Count == 1)
        //                {
        //                    if (CutPhotoidList.Count == 0)
        //                    {
        //                        CanPutWaste = currWate;
        //                        CutPhotoidList = new List<int>();
        //                        foreach (PhotoInfo_PinBan photoct in resultList)
        //                        {
        //                            CutPhotoidList.Add(photoct.PhotoId);
        //                        }
        //                        currRectang.Height = currRectang.Width = 0;
        //                        break;//直接出因为没有照片了
        //                    }
        //                    if (VerticalLine.FirstOrDefault().StartPoint.X >= suitMinX)//已经达到出版最佳尺寸
        //                    {
        //                        break;
        //                    }
        //                    else//当不够设定的最佳尺寸时
        //                    {
        //                        ///1回滚
        //                        break;
        //                    }

        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                throw new Exception("判断是否结束出错" + ex.InnerException);
        //            }

        //            //}
        //            ///建立剩余空白版就是未找到的那块放入List
        //            ///空白块分两种一种是横向一种是竖向实际是检查上下两个方向的x取小的
        //            ///块的宽需要计算得出而不是当前操作快的宽度
        //            //查找空白框的顶点所在的那个照片块
        //            MyRectangle priRect = null;
        //            int balckRWidth = 0;

        //            //if (VerticalLine == null)
        //            //{
        //            //    throw new Exception("VerticalLine为空");
        //            //}

        //            //重新写的填充小块的方法
        //            Line firstLine = null;

        //            try
        //            {
        //                firstLine = VerticalLine.OrderBy(p => p.StartPoint, new MyPointComparer()).FirstOrDefault();
        //            }
        //            catch (Exception ex) { new Exception("获取firstLine出错"); };

        //            if (firstLine == null)
        //            {
        //                if (TSPlist.Count == 0)
        //                {
        //                    break;
        //                }
        //                // 理论不可以
        //                //下一个轮回
        //                sourcePList.ForEach(p => p.IsInBoard = false);

        //                resultList = new List<PhotoInfo_PinBan>();
        //                VerticalLine = new List<Line>();
        //                listRect = new List<MyRectangle>();
        //                currRectang = new Rectangle(new Point(0, 0), new Size(boardLenght, boardHeight));//当前矩形框
        //                continue;
        //            }

        //            Point BlackLocation = firstLine.StartPoint;
        //            int BlackH = firstLine.EndPoint.Y - firstLine.StartPoint.Y;
        //            int TopLeft = 0, BottomLeft = 0;
        //            //查找他的上面的矩形   下边Y值等于Location里的Y, X位于矩形内
        //            MyRectangle TopRect = null;
        //            try
        //            {
        //                TopRect = listRect.Where(r => r.PRactangle.Location.Y + r.PRactangle.Height == BlackLocation.Y && BlackLocation.X >= r.PRactangle.Location.X && BlackLocation.X < r.PRactangle.Location.X + r.PRactangle.Width).FirstOrDefault();
        //                if (TopRect == null)
        //                {
        //                    TopLeft = -1;//上面没有了
        //                }
        //                else
        //                {
        //                    TopLeft = TopRect.PRactangle.Location.X + TopRect.PRactangle.Width - BlackLocation.X;
        //                }

        //                //查找他的下面的矩形   上边Y值等于firstLine终点的Y,   X位于矩形内
        //                MyRectangle BottomRect = listRect.Where(r => r.PRactangle.Location.Y == firstLine.EndPoint.Y && firstLine.EndPoint.X >= r.PRactangle.Location.X && firstLine.EndPoint.X < r.PRactangle.Location.X + r.PRactangle.Width).FirstOrDefault();

        //                if (BottomRect == null)
        //                {
        //                    BottomLeft = -1;//下面没有了
        //                }
        //                else
        //                {
        //                    BottomLeft = BottomRect.PRactangle.Location.X + BottomRect.PRactangle.Width - firstLine.EndPoint.X;
        //                }
        //                //计算要用空白补充的最小单位
        //                if (TopLeft == -1 && BottomLeft != -1)
        //                {
        //                    balckRWidth = BottomLeft;
        //                }
        //                else if (TopLeft != -1 && BottomLeft == -1)
        //                {
        //                    balckRWidth = TopLeft;
        //                }
        //                else if (TopLeft != -1 && BottomLeft != -1)
        //                {
        //                    if (TopLeft >= BottomLeft)
        //                    {
        //                        balckRWidth = BottomLeft;
        //                    }
        //                    else
        //                    {
        //                        balckRWidth = TopLeft;
        //                    }
        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                throw new Exception("判断空白位置出错" + ex.InnerException.ToString());
        //            }

        //            try
        //            {
        //                MyRectangle BlackRect = new MyRectangle(new Rectangle(currRectang.Location, new Size(balckRWidth, currRectang.Size.Height)));
        //                BlackRect.isUsefull = false;
        //                if (BlackRect.PRactangle.Location.X + BlackRect.PRactangle.Width > maxWidth)
        //                {
        //                    balckRWidth = maxWidth;
        //                }
        //                listRect.Add(BlackRect);//找不到合适的照片用白板代替应该控制白板的大小
        //                //记录当前的竖线集合以便找到下一个矩形框
        //                VerticalLine.Remove(VerticalLine.FirstOrDefault(p => p.StartPoint == BlackRect.PRactangle.Location));

        //                Point startPoint = new Point(BlackRect.PRactangle.Location.X + BlackRect.PRactangle.Width, BlackRect.PRactangle.Y);
        //                Point endPoint = new Point(BlackRect.PRactangle.Location.X + BlackRect.PRactangle.Width, BlackRect.PRactangle.Y + BlackRect.PRactangle.Height);

        //                AddLine(ref VerticalLine, new Line(startPoint, endPoint));

        //                //}

        //                //将继续找下一个可以填充的块如果找不到情况重试
        //                //获取最小的位置值XY 都是最小的
        //                firstLine = VerticalLine.OrderBy(p => p.StartPoint, new MyPointComparer()).FirstOrDefault();
        //                int minX = firstLine.StartPoint.X;
        //                if (minX == 11998)
        //                {

        //                }
        //                int minY = firstLine.StartPoint.Y;
        //                if (firstLine.EndPoint.Y > boardHeight)
        //                {

        //                }
        //                CurrVLinePhotoPoint = GetFocusPoint(listRect, firstLine);
        //                int Height = firstLine.EndPoint.Y - firstLine.StartPoint.Y;//下个矩形的高等于线的高度
        //                int Width = boardLenght - minX;//下个矩形的长度等于版长减去minx定点的横坐标
        //                currWidth = currRectang.Width;
        //                Rectangle newrang = new Rectangle(new Point(minX, minY), new Size(Width, Height));

        //                currRectang = newrang;
        //                continue;//继续填充
        //            }
        //            catch (Exception ex)
        //            {
        //                throw new Exception("计算下一个矩形出错");
        //            }

        //            //}
        //            #endregion
        //            //}
        //            //catch (Exception ex)
        //            //{
        //            //    throw new Exception("补空白出错" +ex.InnerException);
        //            //}
        //        }
        //        else
        //        {
        //            //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "获取到第一组照片");

        //            if (listRect.Count == 0)//第一张照片
        //            {
        //                try
        //                {
        //                    #region//第一张照片
        //                    // FristSize=PhotoList.FirstOrDefault().PSize;
        //                    MyRectangle photoRect = null;
        //                    CanPut = false;
        //                    bool isFirstPhoto = true;
        //                    int MaxWidth = 0;
        //                    foreach (PhotoInfo_PinBan photo in PhotoList)
        //                    {
        //                        MyRectangle myr = new MyRectangle(photo);
        //                        myr.isUsefull = true;
        //                        listRect.Add(myr);
        //                        photo.IsInBoard = true;

        //                        //AddInBoardNum(sourcePList ,photo.OrderProductId);

        //                        resultList.Add(photo);
        //                        photoRect = myr;
        //                        //photo.TryTime++;
        //                        ////标记照片已经拼版了包含了副本
        //                        sourcePList.Where(xp => xp.PhotoId == photo.PhotoId).ToList().ForEach(p => p.IsInBoard = true);
        //                        //if (isFirstPhoto)
        //                        //{
        //                        //    photo.TryTime++;
        //                        //    isFirstPhoto = false;
        //                        //}

        //                        #region///验证用

        //                        #endregion
        //                        ////VerticalLine.Remove(VerticalLine.FirstOrDefault(p => p.StartPoint == currRectang.Location));

        //                        outCurrLength = myr.PRactangle.Location.X + myr.PRactangle.Width;//计算当前最长的数字
        //                        if (MaxWidth < outCurrLength)
        //                        {
        //                            MaxWidth = outCurrLength;
        //                        }
        //                        Line delLine = VerticalLine.FirstOrDefault(p => p.StartPoint == myr.PRactangle.Location);
        //                        Point delStartPoint = new Point(0, 0);
        //                        Point delEndPoint = new Point(0, currRectang.Height);
        //                        if (delLine == null)
        //                        {

        //                        }
        //                        else
        //                        {
        //                            delStartPoint = new Point(delLine.StartPoint.X, delLine.StartPoint.Y);
        //                            delEndPoint = new Point(delLine.EndPoint.X, delLine.EndPoint.Y);
        //                        }
        //                        VerticalLine.Remove(delLine);//移除原先的线          
        //                        AddLine(ref VerticalLine, new Line(new Point(myr.PRactangle.X + myr.PRactangle.Width, myr.PRactangle.Y), new Point(myr.PRactangle.X + myr.PRactangle.Width, myr.PRactangle.Y + myr.PRactangle.Height)));
        //                        // VerticalLine.Add();
        //                        AddLine(ref VerticalLine, new Line(new Point(delStartPoint.X, myr.PRactangle.Y + myr.PRactangle.Height), new Point(myr.PRactangle.X, delEndPoint.Y)));
        //                        //VerticalLine.Add();
        //                        //outCurrLength = VerticalLine.Max(p => p.StartPoint.X);
        //                    }

        //                    Line firstLine = VerticalLine.OrderBy(p => p.StartPoint, new MyPointComparer()).FirstOrDefault();
        //                    if (firstLine.EndPoint.Y > boardHeight)
        //                    {

        //                    }
        //                    CurrVLinePhotoPoint = GetFocusPoint(listRect, firstLine);
        //                    int minX = firstLine.StartPoint.X;
        //                    int minY = firstLine.StartPoint.Y;
        //                    int Height = firstLine.EndPoint.Y - firstLine.StartPoint.Y;//下个矩形的高等于线的高度
        //                    int Width = boardLenght - minX;//下个矩形的长度等于版长减去minx定点的横坐标
        //                    currWidth = currRectang.Width;
        //                    Rectangle newrang = new Rectangle(new Point(minX, minY), new Size(Width, Height));
        //                    currRectang = newrang;
        //                    currWate = CheckWaste(listRect, boardHeight);
        //                    if (CanPutWaste >= currWate && outCurrLength >= MinX)
        //                    {
        //                        CanPutWaste = currWate;
        //                        CutPhotoidList = new List<int>();
        //                        foreach (PhotoInfo_PinBan photoct in resultList)
        //                        {
        //                            CutPhotoidList.Add(photoct.PhotoId);
        //                        }
        //                        MyRectangle topRect = listRect.Where(r => r.PRactangle.Y + r.PRactangle.Height == firstLine.StartPoint.Y && firstLine.StartPoint.X >= r.PRactangle.X && firstLine.StartPoint.X <= r.PRactangle.X + r.PRactangle.Width).OrderByDescending(o => o.PRactangle.X + o.PRactangle.Width).FirstOrDefault();
        //                        MyRectangle bottomRect = listRect.Where(r => r.PRactangle.Y == firstLine.EndPoint.Y && firstLine.EndPoint.X >= r.PRactangle.X && firstLine.EndPoint.X <= r.PRactangle.X + r.PRactangle.Width).OrderByDescending(o => o.PRactangle.X + o.PRactangle.Width).FirstOrDefault(); ;

        //                        if (topRect != null && bottomRect != null)
        //                        {
        //                            int topL = topRect.PRactangle.X + topRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            int bottomL = bottomRect.PRactangle.X + bottomRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            if (topL >= bottomL)
        //                            {
        //                                CutRectangle = new Rectangle(new Point(minX, minY), new Size(topL, Height));

        //                            }
        //                            else
        //                            {
        //                                CutRectangle = new Rectangle(new Point(minX, minY), new Size(bottomL, Height));
        //                            }
        //                        }
        //                        else if (topRect == null && bottomRect != null)
        //                        {
        //                            int bottomL = bottomRect.PRactangle.X + bottomRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            CutRectangle = new Rectangle(new Point(minX, minY), new Size(bottomL, Height));
        //                        }
        //                        else if (topRect != null && bottomRect == null)
        //                        {
        //                            int topL = topRect.PRactangle.X + topRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            CutRectangle = new Rectangle(new Point(minX, minY), new Size(topL, Height));
        //                        }
        //                        else
        //                        {
        //                            CutRectangle = new Rectangle(new Point(minX, minY), new Size(0, 0));
        //                        }
        //                    }
        //                    continue;//继续填充

        //                    #endregion
        //                }
        //                catch (Exception ex)
        //                {
        //                    throw new Exception("放第一批照片出错" + ex.StackTrace);
        //                }
        //            }
        //            else
        //            {
        //                //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "获取到版上非第一组照片照片");

        //                try
        //                {
        //                    #region//将照片放到找到的合适的版上
        //                    int tHeight = 0;
        //                    //MyRectangle lastRang = null;
        //                    ///把照片放入找到的暂存块
        //                    MyRectangle photoRect = null;
        //                    foreach (PhotoInfo_PinBan photo in PhotoList)
        //                    {
        //                        MyRectangle myr = new MyRectangle(photo);
        //                        myr.isUsefull = true;
        //                        listRect.Add(myr);//加入暂存块
        //                        //photo.IsInBoard = true;
        //                        resultList.Add(photo);//加入结果列表
        //                        //lastRang = myr;
        //                        photoRect = myr;
        //                        //标记照片已经拼版了包含了副本
        //                        sourcePList.Where(xp => xp.PhotoId == photo.PhotoId).ToList().ForEach(p => p.IsInBoard = true);
        //                        //tempHeight+=myr.PRactangle.Height;

        //                        //实际照片块

        //                        var templist = VerticalLine.Where(p => p.StartPoint.X == myr.PRactangle.Location.X && p.StartPoint.Y <= myr.PRactangle.Location.Y && p.EndPoint.Y >= myr.PRactangle.Location.Y);
        //                        if (templist.Count() == 0)
        //                        {

        //                        }
        //                        Line delLine = templist.FirstOrDefault();
        //                        if (delLine.StartPoint.Y == myr.PRactangle.Y)
        //                        {
        //                            if (delLine == null)
        //                            {
        //                            }
        //                            Line newLine = new Line(new Point(myr.PRactangle.Location.X, myr.PRactangle.Location.Y), new Point(myr.PRactangle.Location.X, myr.PRactangle.Location.Y + myr.PRactangle.Height));//照片所在左边的
        //                            if (newLine == null)
        //                            {

        //                            }
        //                            List<Line> lines = delLine.SubtractLine(newLine);
        //                            if (lines.Count > 1)
        //                            {

        //                            }
        //                            Point delStartPoint = new Point(delLine.StartPoint.X, delLine.StartPoint.Y);
        //                            Point delEndPoint = new Point(delLine.EndPoint.X, delLine.EndPoint.Y);
        //                            VerticalLine.Remove(delLine);//移除原先的线                      
        //                            AddLine(ref VerticalLine, new Line(new Point(myr.PRactangle.Location.X + myr.PRactangle.Width, myr.PRactangle.Location.Y), new Point(myr.PRactangle.Location.X + myr.PRactangle.Width, myr.PRactangle.Location.Y + myr.PRactangle.Height)));//画照片右边的线

        //                            //AddLine(ref VerticalLine, new Line(new Point(myr.PRactangle.Location.X, myr.PRactangle.Location.Y + myr.PRactangle.Height), new Point(delEndPoint.X, delEndPoint.Y)));//画照片下面左边的线
        //                            foreach (Line l in lines)
        //                            {
        //                                AddLine(ref VerticalLine, l);
        //                            }
        //                        }
        //                        else
        //                        {
        //                            VerticalLine.Remove(delLine);//移除原先的线 
        //                            AddLine(ref VerticalLine, new Line(new Point(delLine.StartPoint.X, delLine.StartPoint.Y), new Point(myr.PRactangle.X, myr.PRactangle.Y)));
        //                            AddLine(ref VerticalLine, new Line(new Point(delLine.StartPoint.X + myr.PRactangle.Width, myr.PRactangle.Y), new Point(delLine.StartPoint.X + myr.PRactangle.Width, myr.PRactangle.Y + myr.PRactangle.Height)));
        //                            AddLine(ref VerticalLine, new Line(new Point(myr.PRactangle.X, myr.PRactangle.Y + myr.PRactangle.Height), new Point(delLine.EndPoint.X, delLine.EndPoint.Y)));

        //                        }

        //                        //List<Line> lines=
        //                    }
        //                    Line lengthL = VerticalLine.OrderByDescending(p => p.StartPoint, new MyPointComparer()).FirstOrDefault();
        //                    outCurrLength = lengthL.StartPoint.X;

        //                    //记录当前的竖线集合以便找到下一个矩形框
        //                    //获取最小的位置值XY 都是最小的
        //                    Line firstLine = VerticalLine.OrderBy(p => p.StartPoint, new MyPointComparer()).FirstOrDefault();
        //                    if (firstLine.EndPoint.Y > boardHeight)
        //                    {

        //                    }

        //                    CurrVLinePhotoPoint = GetFocusPoint(listRect, firstLine);

        //                    int minX = firstLine.StartPoint.X;
        //                    int minY = firstLine.StartPoint.Y;
        //                    int Height = firstLine.EndPoint.Y - firstLine.StartPoint.Y;//下个矩形的高等于线的高度
        //                    int Width = boardLenght - minX;//下个矩形的长度等于版长减去minx定点的横坐标
        //                    currWidth = currRectang.Width;
        //                    Rectangle newrang = new Rectangle(new Point(minX, minY), new Size(Width, Height));

        //                    currRectang = newrang;

        //                    ///当前放进去的浪费率
        //                    currWate = CheckWaste(listRect, boardHeight);
        //                    if (CanPutWaste >= currWate && outCurrLength >= MinX)
        //                    {
        //                        CanPutWaste = currWate;
        //                        CutPhotoidList = new List<int>();
        //                        foreach (PhotoInfo_PinBan photoct in resultList)
        //                        {
        //                            CutPhotoidList.Add(photoct.PhotoId);
        //                        }
        //                        MyRectangle topRect = listRect.Where(r => r.PRactangle.Y + r.PRactangle.Height == firstLine.StartPoint.Y && firstLine.StartPoint.X >= r.PRactangle.X && firstLine.StartPoint.X <= r.PRactangle.X + r.PRactangle.Width).OrderByDescending(o => o.PRactangle.X + o.PRactangle.Width).FirstOrDefault();
        //                        MyRectangle bottomRect = listRect.Where(r => r.PRactangle.Y == firstLine.EndPoint.Y && firstLine.EndPoint.X >= r.PRactangle.X && firstLine.EndPoint.X <= r.PRactangle.X + r.PRactangle.Width).OrderByDescending(o => o.PRactangle.X + o.PRactangle.Width).FirstOrDefault(); ;

        //                        if (topRect != null && bottomRect != null)
        //                        {
        //                            int topL = topRect.PRactangle.X + topRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            int bottomL = bottomRect.PRactangle.X + bottomRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            if (topL >= bottomL)
        //                            {
        //                                CutRectangle = new Rectangle(new Point(minX, minY), new Size(topL, Height));

        //                            }
        //                            else
        //                            {
        //                                CutRectangle = new Rectangle(new Point(minX, minY), new Size(bottomL, Height));
        //                            }
        //                        }
        //                        else if (topRect == null && bottomRect != null)
        //                        {
        //                            int bottomL = bottomRect.PRactangle.X + bottomRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            CutRectangle = new Rectangle(new Point(minX, minY), new Size(bottomL, Height));
        //                        }
        //                        else if (topRect != null && bottomRect == null)
        //                        {
        //                            int topL = topRect.PRactangle.X + topRect.PRactangle.Width - firstLine.StartPoint.X;
        //                            CutRectangle = new Rectangle(new Point(minX, minY), new Size(topL, Height));
        //                        }
        //                        else
        //                        {
        //                            CutRectangle = new Rectangle(new Point(minX, minY), new Size(0, 0));
        //                        }

        //                    }
        //                    continue;//继续填充
        //                }
        //                catch (Exception ex)
        //                {
        //                    throw new Exception("放置照片出错" + ex.StackTrace);
        //                }

        //                    #endregion

        //            }
        //        }

        //        //}
        //        //catch (Exception ex)
        //        //{
        //        //    throw new Exception("计算出错1");
        //        //}

        //    }

        //    if (currWate < 0)
        //    {
        //        currWate = 0.001;
        //    }

        //    outWaste = (decimal)currWate;

        //    List<PhotoInfo_PinBan> rtnList = new List<PhotoInfo_PinBan>();
        //    // WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "获取照片完毕");

        //    try
        //    {
        //        ///回滚获取照片列表
        //        int iCount = 0;
        //        //CutPhotoidList = new List<int>();
        //        foreach (PhotoInfo_PinBan photo in resultList)
        //        {
        //            if (CutPhotoidList.Contains(photo.PhotoId))
        //            {

        //                rtnList.Add(photo);
        //                photo.IsInBoard = true;
        //            }
        //            else
        //            {
        //                photo.IsInBoard = false;
        //                //photo.TryTime = 0;
        //                //SubtractInBoardNum(sourcePList, photo.OrderProductId);
        //            }
        //            iCount++;
        //        }
        //        //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "正在回滚");

        //        //回滚结束后 填补回滚块
        //        List<PhotoInfo_PinBan> PhotoBackList = new List<PhotoInfo_PinBan>();
        //        int leftLength = 0;
        //        if (CutRectangle.Width != 0 || CutRectangle.Height != 0)
        //        {
        //            PhotoBackList = FindSuitPhotosForce(sourcePList.Where(p => p.IsInBoard == false).ToList(), CutRectangle, template.BarCodeStatus, out leftLength, sourcePList, 0, template, CurentPrinter, 0, CurrVLinePhotoPoint);
        //        }
        //        if (PhotoBackList != null && PhotoBackList.Count != 0)
        //        {
        //            foreach (PhotoInfo_PinBan photo in PhotoBackList)
        //            {
        //                photo.IsInBoard = true;
        //                rtnList.Add(photo);
        //            }
        //        }

        //        ///计算版长
        //        if (rtnList.Count > 0)
        //        {
        //            outCurrLength = rtnList.Max(p => p.Location.X + (p.IsWhirl ? p.PixFactHeigth : p.PixFactWidth) + ((p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft) ? BARCODEWIDTH : 0));
        //        }
        //        ///计算浪费率
        //        decimal photoAreas = 0;
        //        foreach (PhotoInfo_PinBan photo in rtnList)
        //        {
        //            if (photo.IsWhirl)
        //            {
        //                if (photo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)
        //                {

        //                    photoAreas += (photo.PixFactWidth) * (photo.PixFactHeigth + BARCODEWIDTH);
        //                }
        //                else if (photo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom)
        //                {
        //                    photoAreas += (photo.PixFactWidth + BARCODEWIDTH) * photo.PixFactHeigth;
        //                }
        //                else
        //                {
        //                    photoAreas += (photo.PixFactWidth) * (photo.PixFactHeigth);
        //                }
        //            }
        //            else
        //            {
        //                if (photo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)
        //                {
        //                    photoAreas += (photo.PixFactWidth + BARCODEWIDTH) * photo.PixFactHeigth;
        //                }
        //                else if (photo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom)
        //                {
        //                    photoAreas += (photo.PixFactWidth) * (photo.PixFactHeigth + BARCODEWIDTH);
        //                }
        //                else
        //                {
        //                    photoAreas += (photo.PixFactWidth) * (photo.PixFactHeigth);
        //                }
        //            }

        //        }
        //        if (outCurrLength != 0)
        //        {
        //            outWaste = 1 - photoAreas / ((decimal)outCurrLength * boardHeight);
        //        }
        //        else
        //        {
        //            outWaste = 0;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("计算出错2");
        //    }

        //    //int maxY = rtnList.Max(p => p.Location.Y + (p.IsWhirl ? p.PixFactWidth : p.PixFactHeigth));
        //    //int maxy2 = rtnList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.PixWidth) / p.DPI * CurentPrinter.PDPI) : Convert.ToInt32(((double)p.PixHeight) / p.DPI * CurentPrinter.PDPI)));
        //    return rtnList;
        //}
        ///// <summary>
        private void Re_AutoPB(ref List<PhotoInfo_PinBan> sourPList, Point r_StartPoint, Size r_Size, ref List<PhotoInfo_PinBan> resultPList,
                                int barCodeStatus) //自动拼剩余空间的自动拼板
        {
            Point XDstart_Point = new Point(0, 0); //待拼板区域的相对坐标
            List<PhotoInfo_PinBan> TSPlist; //TSPlist:Temp Source Picture List
            Point re_Point1 = new Point(0, 0); //剩余空间1的起始坐标
            Size re_Size1 = new Size(0, 0); //剩余空间1的SIZE
            Point re_Point2 = new Point(0, 0); //剩余空间2的起始坐标
            Size re_Size2 = new Size(0, 0); //剩余空间2的SIZE
            Point re_Point3 = new Point(0, 0); //剩余空间3的起始坐标
            Size re_Size3 = new Size(0, 0); //剩余空间3的SIZE
            TSPlist =
                sourPList.Where(
                    p =>
                    !p.IsInBoard &&
                    ((p.PixHeight <= r_Size.Height && p.PixWidth <= r_Size.Width) || (p.PixHeight <= r_Size.Width && p.PixWidth <= r_Size.Height)))
                        .OrderByDescending(p => p.PixHeight)
                        .ToList(); //按高度从大到小排序
            if (TSPlist == null || TSPlist.Count < 1)
            {
                return;
            }
            foreach (IGrouping<Size, PhotoInfo_PinBan> item in TSPlist.GroupBy(p => p.PSize, new MySizeComparer()).ToList())
            {
                int colum_row = 0; //每一列可以放入多少个同SIZE的图片
                int colums_fact = 0; //此类尺寸的图片实际有多少列
                int picNum = 0; //实际排了多少张此类尺寸的图片
                Size s = item.Key; //就是能放入剩余空间的图片SIZE的模板，与此模板相同的图片iswhirl=false 相反的就是true;

                #region 找到适合这一区哉能拼的那类图片的集合

                if (XDstart_Point.X + s.Width > r_Size.Width || XDstart_Point.Y + s.Height > r_Size.Height)
                {
                    if (XDstart_Point.X + s.Height > r_Size.Width || XDstart_Point.Y + s.Width > r_Size.Height)
                    {
                        continue;
                    }
                    s.Width = item.Key.Height;
                    s.Height = item.Key.Width;
                }
                if (barCodeStatus != 2)
                {
                    if (barCodeStatus == 1)
                    {
                        s.Width += BARCODEWIDTH;
                    }
                    else
                    {
                        s.Height += BARCODEWIDTH;
                    }
                }
                colum_row = r_Size.Height / s.Height;
                int row_colum = r_Size.Width / s.Width;
                if (colum_row < 1 || row_colum < 1)
                {
                    continue;
                }

                #endregion

                //找到这类集合后对这些图片进行全拼板
                foreach (PhotoInfo_PinBan p in item.OrderByDescending(pt => pt.Priority).ToList()) //按加急级别排倒序的同一SIZE的图片
                {
                    #region 在某一区哉里对相同尺寸的照片进行拼板

                    if (p.IsInBoard)
                    {
                        continue;
                    }
                    if (XDstart_Point.Y + s.Height > r_Size.Height)
                    {
                        if (XDstart_Point.X + 2 * s.Width > r_Size.Width)
                        {
                            break; //此区域内不能再放下相同尺寸的照片了
                        }
                        XDstart_Point.Y = 0;
                        XDstart_Point.X += s.Width;
                    }
                    if (barCodeStatus == 1)
                    {
                        if (s.Width - BARCODEWIDTH == p.PixHeight)
                        {
                            p.IsWhirl = true;
                        }
                    }
                    else //条码在下方或是无条码
                    {
                        if (s.Width == p.PixHeight)
                        {
                            p.IsWhirl = true;
                        }
                    }
                    p.Location = new Point(r_StartPoint.X + XDstart_Point.X, r_StartPoint.Y + XDstart_Point.Y);
                    p.BarCodeStatus = barCodeStatus;
                    p.IsInBoard = true;
                    p.IsAutoPB = true;
                    if (resultPList.Find(pt => pt.PhotoId == p.PhotoId) == null)
                    {
                        resultPList.Add(p);
                        XDstart_Point.Y += s.Height;
                        picNum++;
                    }
                    else
                    {
                        Debug.WriteLine("同一张图片被自动拼板拼了二次!" + p.PhotoId);
                    }

                    #endregion
                }
                if (picNum == 0) //此类尺寸的图片一个都不行，就换下一类尺寸的图片
                {
                    continue;
                }

                #region 得到各自相应的剩余可拼板的区哉

                if (picNum <= colum_row) //只有一列
                {
                    re_Point1 = new Point(XDstart_Point.X, picNum * s.Height);
                    re_Size1 = new Size(s.Width, r_Size.Height - re_Point1.Y);
                    re_Point2 = new Point(s.Width, 0);
                    re_Size2 = new Size(r_Size.Width - s.Width, r_Size.Height);
                }
                else
                {
                    colums_fact = picNum / colum_row; //排满的列数
                    if (picNum % colum_row == 0) //刚好排满几列
                    {
                        re_Point1 = new Point(0, colum_row * s.Height);
                        re_Size1 = new Size(s.Width * colums_fact, r_Size.Height - re_Point1.Y);
                        re_Point2 = new Point(s.Width * colums_fact, 0);
                        re_Size2 = new Size(r_Size.Width - re_Point2.X, r_Size.Height);
                    }
                    else
                    {
                        re_Point1 = new Point(0, colum_row * s.Height);
                        re_Size1 = new Size(s.Width * colums_fact, r_Size.Height - re_Point1.Y);
                        re_Point2 = new Point(s.Width * colums_fact, s.Height * (picNum % colum_row));
                        re_Size2 = new Size(s.Width, r_Size.Height - re_Point2.Y);
                        re_Point3 = new Point(s.Width * colums_fact + s.Width, 0);
                        re_Size3 = new Size(r_Size.Width - re_Point3.X, r_Size.Height);
                    }
                }

                #endregion

                #region 递归对各个区哉进行全自动拼板算法

                if (re_Size1.Width > 0 && re_Size1.Height > 0)
                {
                    re_Point1.Offset(r_StartPoint);
                    Re_AutoPB(ref sourPList, re_Point1, re_Size1, ref resultPList, barCodeStatus);
                }
                if (re_Size2.Width > 0 && re_Size2.Height > 0)
                {
                    re_Point2.Offset(r_StartPoint);
                    Re_AutoPB(ref sourPList, re_Point2, re_Size2, ref resultPList, barCodeStatus);
                }
                if (re_Size3.Width > 0 && re_Size3.Height > 0)
                {
                    re_Point3.Offset(r_StartPoint);
                    Re_AutoPB(ref sourPList, re_Point3, re_Size3, ref resultPList, barCodeStatus);
                }

                #endregion

                break;
            }
        }
        public int ZFPhoto(List<int> PIdList, int printerId) //将LIST照片转发到指定的打印机
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                foreach (int pid in PIdList)
                {
                    photoInfo pi = dataBase.photoInfo.FirstOrDefault(p => p.photoId == pid);
                    printer print = dataBase.printer.FirstOrDefault(p => p.PrinterID == printerId);
                    if (pi != null)
                    {
                        pi.pixWidth = (int)(pi.Width * print.PDPI);
                        pi.pixHeight = (int)(pi.Height * print.PDPI);
                        pi.printerId = printerId;
                    }
                }
                try
                {
                    dataBase.SaveChanges();
                }
                catch (Exception)
                {
                    return 0;
                }
            }
            return 1;
        }

        #region 辅助比较类

        private class MyOrderInfoCompare : IEqualityComparer<orderInfo> //辅助类，用于比较orderInfo
        {
            #region IEqualityComparer<orderInfo> 成员

            public bool Equals(orderInfo x, orderInfo y)
            {
                if (x.OrderProductId == y.OrderProductId)
                {
                    return true;
                }
                return false;
            }
            public int GetHashCode(orderInfo obj)
            {
                return obj.GetHashCode();
            }

            #endregion
        }

        private class MyPhotoComparer : IEqualityComparer<PhotoInfo_PinBan>
        {
            #region IEqualityComparer<PhotoInfo_PinBan> 成员

            public bool Equals(PhotoInfo_PinBan x, PhotoInfo_PinBan y)
            {
                if (x.PhotoId == y.PhotoId)
                {
                    return true;
                }
                return false;
            }
            public int GetHashCode(PhotoInfo_PinBan obj)
            {
                //return obj.GetHashCode();
                return -1;
            }

            #endregion
        }

        public class MySizeComparer : IEqualityComparer<Size>
        {
            #region IEqualityComparer<Size> 成员

            public bool Equals(Size x, Size y)
            {
                if ((x.Width == y.Width && x.Height == y.Height) || (x.Width == y.Height && x.Height == y.Width))
                {
                    return true;
                }
                return false;
            }
            public int GetHashCode(Size obj)
            {
                //return obj.GetHashCode();
                return -1; //如果是值的话就返回-1
            }

            #endregion
        }

        #endregion

        /// 获取一组照片
        /// </summary>
        /// <param name="inList">可用照片列表</param>
        /// <param name="currRang">当前填充矩形框</param>
        /// <param name="barCodeStatus">条码放置方向</param>
        /// <param name="LeftH">剩余高度</param>
        /// <param name="AllList"></param>
        /// <param name="putPhotoOrder">照片放置宽度顺序</param>
        /// <param name="template">当前模板</param>
        /// <param name="CurentPrinter">当前打印机</param>
        /// <param name="MinLength">最小版长</param>
        /// <param name="autoModel">拼版模式</param>
        /// ///
        /// <param name="inVPoint">当前竖线上的照片点</param>
        /// <returns></returns>
        //List<PhotoInfo_PinBan> FindSuitPhotos21(List<PhotoInfo_PinBan> inList, Rectangle currRang, PhotoBarCodeStatus barCodeStatus, out int LeftH, List<PhotoInfo_PinBan> AllList, int putPhotoOrder, Tb_paperTemplate_Info template, Printer_Info CurentPrinter, int MinLength, int aotuModel, List<Point> inVPoint)
        //{

        //    int inHeigth = currRang.Height; int MaxWidth = currRang.Width;
        //    //var TEMP = inList.Where(g => g.PixFactWidth <= MaxWidth);
        //    //var TEMP1 inList= .Where(g => g.PixFactHeigth <= inHeigth);
        //    //var TEMP2 = inList.Where(g => g.PixFactWidth <= MaxWidth && g.PixFactHeigth <= inHeigth).OrderBy(or => or.PixFactHeigth);
        //    var photoSizeGroup = inList.Where(g => (g.PixFactWidth <= MaxWidth && g.PixFactHeigth <= inHeigth) || (g.PixFactWidth <= inHeigth && g.PixFactHeigth <= MaxWidth)).OrderByDescending(or => or.PixFactHeigth).GroupBy(p => p.PhotoSizePix).ToList();
        //    if (photoSizeGroup.Count() == 0)
        //    {
        //        LeftH = currRang.Height;
        //        return null;
        //    }
        //    photoSizeGroup = photoSizeGroup.OrderByDescending(or => or.FirstOrDefault().PixFactHeigth).ToList();

        //    int sizeCount = photoSizeGroup.Count();
        //    iMageInfo[] sizeArray = new iMageInfo[sizeCount + 1];
        //    for (int i = 1; i <= sizeCount; i++)
        //    {
        //        iMageInfo sizeG = new iMageInfo();
        //        sizeG.Width = photoSizeGroup[i - 1].FirstOrDefault().PixFactWidth;
        //        sizeG.Height = photoSizeGroup[i - 1].FirstOrDefault().PixFactHeigth;
        //        sizeG.Count = photoSizeGroup[i - 1].Count();

        //        sizeArray[i] = sizeG;
        //    }
        //    int[] UseBlackWidth = new int[3];
        //    int[] UseComboxNum = new int[3];
        //    int[] UseCountLevel = new int[3];
        //    if (aotuModel == 0)
        //    {
        //        UseBlackWidth = BlackWidthLong;
        //        UseComboxNum = ComboxNumLong;
        //        UseCountLevel = CountLevelLong;
        //    }
        //    else if (aotuModel == 1)
        //    {
        //        UseBlackWidth = BlackWidthLowWaste;
        //        UseComboxNum = BlackWidthLowWaste;
        //        UseCountLevel = BlackWidthLowWaste;
        //    }
        //    else
        //    {
        //        UseBlackWidth = BlackWidthLong;
        //        UseComboxNum = ComboxNumLong;
        //        UseCountLevel = CountLevelLong;
        //    }
        //    //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "源有"+sizeArray+"组照片");
        //    //foreach (var aa in sizeArray)
        //    //{
        //    //    int bb = 1;
        //    //    WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "aa=" + " " + aa.Width + " " + aa.Height + " " );
        //    //    bb++;
        //    //}
        //    Array array = sizeArray;
        //    //第一个参数 数组，第二个第三个 是宽高第四个是条码宽第五个是 容错宽 第六个是组合数 第7个一次取最多尺寸数
        //    Array sizeResult = null;
        //    int barcodeWidth = 30;
        //    if (barCodeStatus == PhotoBarCodeStatus.NoBarCode)
        //    {
        //        barcodeWidth = 0;
        //    }
        //    int tempLevel = changeLevel;
        //leableA:
        //    try
        //    {
        //        int currBlank = Convert.ToInt32(((float)UseBlackWidth[tempLevel] * 7620 / (template.BoardHeight * CurentPrinter.PDPI) / 100) * inHeigth);
        //        if (currBlank > 1500)
        //        {
        //            currBlank = 1500;
        //        }
        //        //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + tempLevel);
        //        //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + MaxWidth + "|" + inHeigth + "|" + barcodeWidth + "|" + currBlank + "|" + UseComboxNum[tempLevel] + "|" + UseCountLevel[tempLevel]);

        //        sizeResult = InterFace.Function3(ref array, MaxWidth, inHeigth, barcodeWidth, currBlank, UseComboxNum[tempLevel], UseCountLevel[tempLevel]);//
        //    }
        //    catch (Exception ex)
        //    {
        //        // WriteLogForCheck.WriteLogFile(DateTime.Now + ":调用Function3出错" + ex.Message);

        //        throw ex;
        //    }
        //    if (sizeResult.Length == 0)
        //    {
        //        throw new Exception("请确认已装入加密狗后再试");
        //    }

        //    iMageInfo[] arrResult = (iMageInfo[])sizeResult;
        //    //foreach (var aa in arrResult)
        //    //{
        //    //    int bb = 1;
        //    //    WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "aa=" + " " + aa.Width + " " + aa.Height + " ");
        //    //    bb++;
        //    //}

        //    //此处为处理找不到片子时放宽Level
        //    if (arrResult[0].Count == 0)
        //    {
        //        if (tempLevel > 2)
        //        {
        //            // WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "tempLevel=" + tempLevel);

        //            LeftH = 0;
        //            return new List<PhotoInfo_PinBan>();
        //        }
        //        else
        //        {
        //            tempLevel++;
        //            goto leableA;
        //        }

        //    }

        //    //此处判断小片

        //    int maxphotoWidth = arrResult.Max(p => p.Width);
        //    int maxphotoHeight = arrResult.Max(p => p.Height);
        //    //decimal colphotoNum = (decimal)template.Height / template.MinPhotoSize;
        //    if ((maxphotoWidth <= template.MinPhotoSize * CurentPrinter.PDPI && maxphotoHeight < template.MinPhotoSize * CurentPrinter.PDPI) && currRang.Height >= template.Height * CurentPrinter.PDPI * 0.5)
        //    {
        //        if (tempLevel < 2)
        //        {
        //            tempLevel++;
        //            goto leableA;
        //        }
        //        else
        //        {

        //            if (currRang.Height >= template.BoardHeight * CurentPrinter.PDPI * 0.5 && currRang.X >= MinLength)
        //            {
        //                int testoutHeightLeft = 0;
        //                List<PhotoInfo_PinBan> Templist = AllList.Where(p => p.IsInBoard == false && ((p.PixFactHeigth <= template.BoardHeight * CurentPrinter.PDPI && p.PixFactWidth <= template.BoardLength * CurentPrinter.PDPI) || (p.PixFactHeigth <= template.BoardLength * CurentPrinter.PDPI && p.PixFactWidth <= template.BoardHeight * CurentPrinter.PDPI))).ToList(); ;

        //                List<PhotoInfo_PinBan> PhotoTestList = FindSuitPhotos2(Templist, new Rectangle(new Point(0, 0), new Size((int)template.BoardLength * CurentPrinter.PDPI, (int)template.BoardHeight * CurentPrinter.PDPI)), template.BarCodeStatus, out testoutHeightLeft, AllList, 0);

        //                double maxphotoWidthTest = PhotoTestList.Max(p => p.Width);
        //                double maxphotoHeightTest = PhotoTestList.Max(p => p.Height);
        //                if (maxphotoWidthTest <= (double)template.MinPhotoSize && maxphotoWidthTest < (double)template.MinPhotoSize)
        //                {
        //                    //不处理放进版面
        //                }
        //                else
        //                {
        //                    //认为次情况不能取到照片
        //                    LeftH = 0;
        //                    return new List<PhotoInfo_PinBan>();
        //                }

        //            }
        //            else
        //            {
        //                //不处理放进版面
        //            }
        //        }

        //    }

        //    string Key = "";
        //    Dictionary<string, int> sizePair = new Dictionary<string, int>();
        //    List<PhotoInfo_PinBan> suitest = new List<PhotoInfo_PinBan>();

        //    //WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + "suites.count=" + suitest.Count);

        //    Dictionary<int, int> orderAndNum = new Dictionary<int, int>();//orderid和缺少多少张就完成
        //    List<int> AddedPhotoidlist = new List<int>();
        //    for (int i = 0; i < arrResult.Length; i++)
        //    {
        //        List<PhotoInfo_PinBan> suitTemp = new List<PhotoInfo_PinBan>();
        //        var a = inList.Where(p => p.PixFactWidth == arrResult[i].Width && p.PixFactHeigth == arrResult[i].Height);
        //        var b = a.OrderByDescending(or => or.Priority).ThenByDescending(ph => ph.CompletePercent);
        //        int icount = 0;
        //        foreach (var ph in b)
        //        {
        //            if (AddedPhotoidlist.Contains(ph.PhotoId))
        //            {
        //                continue;
        //            }
        //            else
        //            {
        //                AddedPhotoidlist.Add(ph.PhotoId);
        //                suitTemp.Add(ph);
        //                icount++;
        //                if (icount == arrResult[i].Count)
        //                {
        //                    break;
        //                }
        //            }
        //        }
        //        //处理条码
        //        if (barCodeStatus != SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode)
        //        {
        //            if (arrResult[i].barCode == 0)
        //            {
        //                suitTemp.ForEach(eh => eh.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft);

        //            }
        //            else
        //            {
        //                suitTemp.ForEach(eh => eh.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom);
        //            }
        //        }
        //        else
        //        {
        //            suitTemp.ForEach(eh => eh.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode);
        //        }
        //        //处理旋转
        //        if (arrResult[i].isRotate == 1)
        //        {
        //            suitTemp.ForEach(en => en.IsWhirl = true);
        //        }
        //        else
        //        {
        //            suitTemp.ForEach(en => en.IsWhirl = false);
        //        }
        //        suitest.AddRange(suitTemp);

        //    }

        //    //新的获取照片顺序的按照剩余照片最少的 产品的原则获取照片

        //    //确定照片的摆放顺序
        //    //Point leftTop = currRang.Location;//左上定点
        //    //Point leftBottom = new Point(currRang.Location.X, currRang.Location.Y + currRang.Height);//坐下顶点

        //    //suitest.Add(photoSizeGroup.FirstOrDefault());
        //    //suitest = suitest.OrderByDescending(p => (p.IsWhirl) ? p.PixFactHeigth : p.PixFactWidth).ToList();
        //    if (putPhotoOrder == 0)
        //    {
        //        suitest = suitest.OrderBy(p => (p.IsWhirl) ? p.PixFactHeigth : p.PixFactWidth).ToList();
        //    }
        //    else
        //    {
        //        suitest = suitest.OrderByDescending(p => (p.IsWhirl) ? p.PixFactHeigth : p.PixFactWidth).ToList();
        //    }
        //    int col = 0;
        //    int CurrHeight = currRang.Location.Y; ;

        //    foreach (var photo in suitest)
        //    {

        //        //计算合适的 照片的坐标
        //        if (photo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom)
        //        {
        //            if (photo.IsWhirl)
        //            {
        //                photo.Location = new Point(currRang.Location.X, CurrHeight);
        //                CurrHeight += photo.PixFactWidth + BARCODEWIDTH;
        //            }
        //            else
        //            {
        //                photo.Location = new Point(currRang.Location.X, CurrHeight);
        //                CurrHeight += photo.PixFactHeigth + BARCODEWIDTH;
        //            }

        //        }
        //        else if (photo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)
        //        {
        //            if (photo.IsWhirl)
        //            {
        //                photo.Location = new Point(currRang.Location.X, CurrHeight);
        //                CurrHeight += photo.PixFactWidth;
        //            }
        //            else
        //            {
        //                photo.Location = new Point(currRang.Location.X, CurrHeight);
        //                CurrHeight += photo.PixFactHeigth;
        //            }
        //        }
        //        else
        //        {
        //            if (photo.IsWhirl)
        //            {
        //                photo.Location = new Point(currRang.Location.X, CurrHeight);
        //                CurrHeight += photo.PixFactWidth;
        //            }
        //            else
        //            {
        //                photo.Location = new Point(currRang.Location.X, CurrHeight);
        //                CurrHeight += photo.PixFactHeigth;
        //            }
        //        }
        //        //if (photo.Location.X == 0 && photo.Location.Y == 0)
        //        //{

        //        //}

        //    }
        //    int newCurrHeight = suitest.Max(p => p.Location.Y + (p.IsWhirl != true ? p.PixFactHeigth : p.PixFactWidth) + (p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom ? BARCODEWIDTH : 0));
        //    //LeftH = inHeigth - CurrHeight + currRang.Location.Y;//还差多少可以填满
        //    if (newCurrHeight != CurrHeight)
        //    {

        //    }
        //    LeftH = inHeigth - newCurrHeight + currRang.Location.Y;
        //    if (LeftH <= 0)
        //    {

        //    }
        //    else
        //    {

        //        if (inVPoint.Count > 0)
        //        {
        //            Point FirstPoint = inVPoint.Where(p => p.Y >= currRang.Y).OrderBy(or => or.Y).FirstOrDefault();
        //            Point LastPoint = inVPoint.Where(p => p.Y <= currRang.Y + currRang.Height).OrderByDescending(or => or.Y).FirstOrDefault();
        //            int topHeight = FirstPoint.Y - currRang.Y;
        //            if (FirstPoint.Y < currRang.Location.Y)
        //            {

        //            }
        //            else
        //            {
        //                int bottomHeight = currRang.Y + currRang.Height - LastPoint.Y;
        //                if (LeftH < topHeight && LeftH < bottomHeight)
        //                {
        //                    //移动不起作用
        //                }
        //                else if (LeftH <= topHeight && LeftH >= bottomHeight)
        //                {
        //                    //不动默认往上放 但是照片要往下移动的距离靠近缝隙
        //                    foreach (var photo in suitest)
        //                    {
        //                        photo.Location = new Point(photo.Location.X, photo.Location.Y + (LeftH - bottomHeight));

        //                    }

        //                }
        //                else if (LeftH >= topHeight && LeftH <= bottomHeight)
        //                {
        //                    //不动默认往上放 但是照片要往下移动的距离靠近缝隙
        //                    foreach (var photo in suitest)
        //                    {
        //                        photo.Location = new Point(photo.Location.X, photo.Location.Y + topHeight);

        //                    }
        //                }
        //                else if (LeftH > topHeight && LeftH > bottomHeight)
        //                {
        //                    if (topHeight < bottomHeight)
        //                    {
        //                        //不动默认往上放 但是照片要往下移动的距离靠近缝隙
        //                        foreach (var photo in suitest)
        //                        {
        //                            photo.Location = new Point(photo.Location.X, photo.Location.Y + topHeight);

        //                        }
        //                    }
        //                    else
        //                    {
        //                        //不动默认往上放 但是照片要往下移动=的距离靠近缝隙
        //                        foreach (var photo in suitest)
        //                        {
        //                            photo.Location = new Point(photo.Location.X, photo.Location.Y + (LeftH - bottomHeight));

        //                        }
        //                    }
        //                }
        //            }

        //        }

        //        int afterBottomHeight = suitest.Max(p => p.Location.Y + (p.IsWhirl != true ? p.PixFactHeigth : p.PixFactWidth) + (p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom ? BARCODEWIDTH : 0));
        //        if (afterBottomHeight > currRang.Y + currRang.Height)
        //        {

        //        }
        //        int aftertopHeight = suitest.Min(p => p.Location.Y);
        //        if (afterBottomHeight < currRang.Y)
        //        {

        //        }

        //    }
        //    return suitest;

        //}
        ///// <summary>
        private class PhotoSizeCompare : IEqualityComparer<PhotoInfo_PinBan>
        {
            #region IEqualityComparer<PhotoInfo_PinBan> 成员

            //比较二个矩形是否重叠，如果重叠返回TRUE
            public bool Equals(PhotoInfo_PinBan x, PhotoInfo_PinBan y)
            {
                Rectangle XR = new Rectangle(x.Location, x.PSize);
                Rectangle YR = new Rectangle(y.Location, y.PSize);
                if (XR.IntersectsWith(YR))
                {
                    return true;
                }
                return false;
            }
            public int GetHashCode(PhotoInfo_PinBan obj)
            {
                return obj.GetHashCode();
            }

            #endregion
        }
        /// <summary>
        /// /返回失败记录
        /// </summary>
        /// <param name="listToSave"></param>
        /// <returns></returns>
        public List<PhotoInfo_PinBan> AddDXF(List<PhotoInfo_PinBan> listToSave)
        {
            List<PhotoInfo_PinBan> unsaveList = new List<PhotoInfo_PinBan>();
            using (AdoEx database = new AdoEx())
            {
                StringBuilder _bulder = new StringBuilder();
                foreach (var ph in listToSave)
                {
                    string updateSql = "update photoinfo set DXFPath=@dxfpath,DXFContent=@Content where photoid=@photoid";
                    Dictionary<string, object> paras = new Dictionary<string, object>();
                    paras.Add("dxfpath", ph.DXFPath);
                    paras.Add("Content", ph.DXFContent);
                    paras.Add("photoid", ph.PhotoId);
                    int r = database.ExecuteNonQueryEx(CommandType.Text, updateSql, paras);
                    if (r == 0)
                    {
                        unsaveList.Add(ph);
                    }
                }
            }
            return unsaveList;
        }
        /// <summary>
        /// /返回失败记录
        /// </summary>
        /// <param name="listToSave"></param>
        /// <returns></returns>
        public List<PhotoInfo_PinBan> DelDXF(List<PhotoInfo_PinBan> listToSave)
        {
            List<PhotoInfo_PinBan> unsaveList = new List<PhotoInfo_PinBan>();
            using (AdoEx database = new AdoEx())
            {
                StringBuilder _bulder = new StringBuilder();
                foreach (var ph in listToSave)
                {
                    string updateSql = "update photoinfo set DXFPath='',DXFContent=null where photoid=@photoid";
                    Dictionary<string, object> paras = new Dictionary<string, object>();
                    paras.Add("dxfpath", ph.DXFPath);
                    paras.Add("Content", ph.DXFContent);
                    paras.Add("photoid", ph.PhotoId);
                    int r = database.ExecuteNonQueryEx(CommandType.Text, updateSql, paras);
                    if (r == 0)
                    {
                        unsaveList.Add(ph);
                    }
                }
            }
            return unsaveList;
        }
    }


    public class Line
    {
        public Line(Point s, Point e)
        {
            startPoint = s;
            endPoint = e;
        }
        private Point startPoint { get; set; }
        private Point endPoint { get; set; }
        public Point StartPoint
        {
            get { return startPoint; }
            set { startPoint = value; }
        }
        public Point EndPoint
        {
            get { return endPoint; }
            set { endPoint = value; }
        }
        public List<Line> SubtractLine(Line inLine)
        {
            List<Line> rtnList = new List<Line>();
            if (startPoint.Y == inLine.startPoint.Y && endPoint.Y == inLine.endPoint.Y) //同一条线
            {
            }
            else if (startPoint.Y == inLine.startPoint.Y && endPoint.Y != inLine.endPoint.Y) //相同的开头
            {
                Line newline = new Line(inLine.endPoint, endPoint);
                rtnList.Add(newline);
            }
            else if (startPoint.Y != inLine.startPoint.Y && endPoint.Y == inLine.endPoint.Y)
            {
                Line newline = new Line(startPoint, inLine.startPoint);
                rtnList.Add(newline);
            }
            else
            {
                rtnList.Add(new Line(startPoint, inLine.startPoint));
                rtnList.Add(new Line(inLine.endPoint, endPoint));
            }
            return rtnList;
        }
    }
}

    //public class MyRectangle
    //{
    //    int BARCODEWIDTH = 30;
    //    public MyRectangle(PhotoInfo_PinBan inPhoto)
    //    {
    //        myPhoto = inPhoto;
    //        if (inPhoto.BarCodeStatus ==(int)PhotoBarCodeStatus.RightOrLeft)
    //        {
    //            if (inPhoto.IsWhirl)
    //            {
    //                Size size = new Size((inPhoto.PixFactHeigth + BARCODEWIDTH), inPhoto.PixFactWidth);
    //                this.myRact = new Rectangle(inPhoto.Location, size);
    //            }
    //            else
    //            {
    //                Size size = new Size((inPhoto.PixFactWidth + BARCODEWIDTH), inPhoto.PixFactHeigth);
    //                this.myRact = new Rectangle(inPhoto.Location, size);
    //            }
    //        }
    //        else if (inPhoto.BarCodeStatus ==(int)PhotoBarCodeStatus.TopOrBottom)
    //        {
    //            if (Photo.IsWhirl)
    //            {
    //                Size size = new Size((inPhoto.PixFactHeigth), inPhoto.PixFactWidth + BARCODEWIDTH);
    //                this.myRact = new Rectangle(inPhoto.Location, size);
    //            }
    //            else
    //            {
    //                Size size = new Size((inPhoto.PixFactWidth), inPhoto.PixFactHeigth + BARCODEWIDTH);
    //                this.myRact = new Rectangle(inPhoto.Location, size);
    //            }
    //        }
    //        else
    //        {
    //            if (Photo.IsWhirl)
    //            {
    //                Size size = new Size((inPhoto.PixFactHeigth), inPhoto.PixFactWidth);
    //                this.myRact = new Rectangle(inPhoto.Location, size);
    //            }
    //            else
    //            {
    //                Size size = new Size((inPhoto.PixFactWidth), inPhoto.PixFactHeigth);
    //                this.myRact = new Rectangle(inPhoto.Location, size);
    //            }
    //        }
    //        //Size size = new Size(inPhoto.Photo_Base_Info.PixFactWidth, inPhoto.Photo_Base_Info.PixFactHeigth);
    //        //this.myRact = new Rectangle(inPhoto.Location, size);

    //    }
    //    public MyRectangle(Rectangle rant)
    //    {
    //        this.myRact = rant;
    //    }
    //    private Rectangle myRact { get; set; }
    //    private PhotoInfo_PinBan myPhoto { get; set; }
    //    public PhotoInfo_PinBan Photo { get { return myPhoto; } }
    //    public Rectangle PRactangle { get { return this.myRact; } }//当前块
    //    public bool isUsefull { get; set; }//是否包含照片
    //    public double Areas { get { return myRact.Width * myRact.Height; } }
    //    //public MyRectangle LeftRect { get; set; }
    //    //public MyRectangle RightRect { get; set; }
    //    //public MyRectangle TopRect { get; set; }
    //    //public MyRectangle Bottom { get; set; }
    //    public Point LeftTopPoint { get { return myRact.Location; } }
    //    public Point RighTopPoint { get { return new Point(myRact.Location.X + myRact.Width, myRact.Location.Y); } }
    //    public Point LeftBottomPoint { get { return new Point(myRact.Location.X, myRact.Location.Y + myRact.Height); } }
    //    public Point RightBottomPoint { get { return new Point(myRact.Location.X + myRact.Width, myRact.Location.Y + myRact.Height); } }
    //}


